歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android入門:隱式Intent

Android入門:隱式Intent

日期:2017/3/1 10:16:00   编辑:Linux編程

一、隱式意圖介紹


顯式意圖我們前面已經提到,形如:

Intent intent = new Intent();

intent.setClass(this,Other.class);//此句表示顯式意圖,因為明確設置激活對象為Other類

startActivity(intent);


顧名思義,隱式意圖就是在不明確設置激活對象的前提下尋找最匹配的組件,舉個例子,比如有5個人:

(1)A:170cm

(2)B:160cm

(3)C:180cm

(4)D:190cm

(5)E:200cm

如果是顯示意圖的話,如果我們要指明選擇A的話會說:”我選擇A.“,但是如果是隱式意圖,則會說:”我要選擇170cm的人“,雖然沒有指明要選A,但會尋找條件最匹配的人。

在intent過濾器中類似於上面例子中的”身高“條件的匹配條件有:

(1)action

(2)category

(3)data:scheme、host、path、type

當在程序中設置了這些激活組件的條件,程序就會去尋找最匹配的組件,但是注意:只要有一點不匹配,則就是不匹配;

比如:

Intent intent = new Intent();

intent.setAction("a");//此句只是指定了Action

startActivity(intent);//尋找最匹配的組件激活,內部會調用intent.addCategory("Android.intent.category.DEFAULT");


二、隱式Intent的核心代碼


首先是在AndroidManifest.xml中為某個Activity設置意圖過濾器:

  1. <activity>
  2. <intent-filter>
  3. <action android:name="...."/>
  4. <category android:name="...."/>
  5. <category android:name="android.intent.category.DEFAULT"/> <!--此句一般都要加 -->
  6. <data android:scheme="..." android:host="..." android:path="/..." android:type="..."/>
  7. </intent-filter>
  8. </activity>

以上設置是設置Activity本身的屬性,接下來在程序中要設置的是我們要尋找時匹配的條件:

(1)Intent intent = new Intent();

(2)intent.setAction("....");

(3)intent.addCategory("....");

(4)intent.setData(Uri.parse("...."));//設置data的scheme、host、path條件

(5)intent.setDataAndType(Uri.parse(""),String type);//同時設置data的scheme、host、path、type條件

(6)startActivity(intent);//調用intent.addCategory("android.intent.category.DEFAULT");

Copyright © Linux教程網 All Rights Reserved