Android組件之Intent

一、Intent對象及其屬性

1.1 Intent的ComponentName屬性

Intent查找組件策略,顯示方式直接通過組件名稱Component name來查找。Intent的組件名稱對象由ComponentName類來封裝,組件名稱包含包名稱和類名稱,被聲明在AndroidManifest.xml文件中

組件名稱通過setComponent(),setClass(),setClassName()設置,通過getComponent()獲得。

實例DEMO重要代碼:

①在Button單擊方法中創建組件名稱對象,指向一個Activity,實例化Intent,併爲其設置組件名稱屬性,啓動Acticity

public void onClick(View v) {
				//實例化組件名稱
				ComponentName cn = new ComponentName(MainActivity.this, MyActivity.class);
				//實例化Intent
				Intent intent = new Intent();
				//爲Intent設置組件名稱屬性
				intent.setComponent(cn);
				//啓動Activity
				startActivity(intent);
			}

②在另外一個Acticity的onCreate()方法實例化文本框,獲得Intent從而獲得組件名稱對象,從組件名稱對象中獲取包名稱和類名稱

		protected void onCreate(Bundle savedInstanceState) {
			// TODO Auto-generated method stub
			super.onCreate(savedInstanceState);
			setContentView(R.layout.my_layout);
			//獲得intent對象
			Intent intent=getIntent();
			//獲得組件名稱對象
			ComponentName cn = intent.getComponent();
			//獲得包名
			String packageName = cn.getPackageName();
			// 獲得類名稱
			String className = cn.getClassName();
			//實例化TextView
			textView = (TextView)findViewById(R.id.textView1);
			textView.setText(" 組件包名稱:"+packageName+",類名稱:"+className);
		}

1.2 Intent的Action屬性

Action是指Intent要完成的動作,是一個字符串常量。Intent類裏面定義了大量的Action常量屬性,例如ACTION_CALL、ACTION_EDIT、ACTION_BATTEAY_LOW。我們可以自己定義Action來使用。

通過setAction()來設置Intent的Action屬性,使用getAction來獲得Intent的Action屬性。

①自定義Action屬性

爲Intent定義一個Action屬性來訪問,Action屬性是一個字符串。我們在程序中定義,並在要訪問最賤的IntentFilter中聲明就可以。

	/定義Action屬性常量
	private static final String MY_ACTION = "com.hanfeng.intent_action.MY_ACTION";		
	public void onClick(View v) {
				//實例化Intent
				Intent intent = new Intent();
				//爲Intent設置Action屬性
				intent.setAction(MY_ACTION);
				//啓動Activity
				startActivity(intent);
			}

在另外一個Acticity的onCreate()方法實例化文本框,獲得Intent實例,從而獲得屬性並顯示在textView裏面

		protected void onCreate(Bundle savedInstanceState) {			
			super.onCreate(savedInstanceState);
			setContentView(R.layout.my_layout);
			//獲得intent對象
			Intent intent=getIntent();			
			//獲得Action
			String action= intent.getAction();
			//實例化TextView
			textView = (TextView)findViewById(R.id.textView1);
			textView.setText(action);
		}
在AndroidManifest.xml配置文件中添加一個Acticity的聲明,在IntentFilter元素中指定Action屬性

	<activity android:name=".MyActivity" >
            <intent-filter>
                <action android:name="com.hanfeng.acticity。.MY_ACTION" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>


尚未完結筆記



發佈了20 篇原創文章 · 獲贊 3 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章