一、隱式意圖介紹
顯式意圖
Intent intent = new Intent();
intent.setClass(this,Other.class);//此句表示顯式意圖,因?yàn)槊鞔_設(shè)置激活對(duì)象為Other類
startActivity(intent);
隱式意圖在intent過濾器中的匹配條件有:
(1) action
(2) category
(3) data:scheme、host、path、type
當(dāng)在程序中設(shè)置了這些激活組件的條件,程序就會(huì)去尋找最匹配的組件,但是注意:只要有一點(diǎn)不匹配,則就是不匹配;
比如:
Intent intent = new Intent();
intent.setAction("a");//此句只是指定了Action
startActivity(intent);//尋找最匹配的組件激活,內(nèi)部會(huì)調(diào)用intent.addCategory("android.intent.category.DEFAULT");
二、隱式Intent的核心代碼
首先是在AndroidManifest.xml中為某個(gè)Activity設(shè)置意圖過濾器:
<intent-filter>
<action android:name="...."/>
<category android:name="...."/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="..." android:host="..." android:path="/..." android:type="..."/>
</intent-filter>
以上設(shè)置是設(shè)置Activity本身的屬性,接下來在程序中要設(shè)置的是我們要尋找時(shí)匹配的條件:
Intent intent = new Intent();
intent.setAction("....");
intent.addCategory("....");
intent.setData(Uri.parse("...."));//設(shè)置data的scheme、host、path條件
intent.setDataAndType(Uri.parse(""),String type);//同時(shí)設(shè)置data的scheme、host、path、type條件
startActivity(intent);//調(diào)用intent.addCategory("android.intent.category.DEFAULT");
三、示例說明
情況一
<intent-filter>
<action android:name="com.babybus_lion.action" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="com.babybus_lion.category" />
<data
android:host="[www.babybus_lion.com](https://link.jianshu.com?t=http://www.babybus_lion.com)"
android:scheme="babybus_lion"/>
</intent-filter>
代碼為:
Intent intent = new Intent();
intent.setAction("com.babybus_lion.action");
intent.addCategory("com.babybus_lion.category");
intent.setData(uri));
startActivity(intent); //此方法中調(diào)用intent.addCategory("android.intent.category.DEFAULT");
情況二
在<data>中多了一個(gè)android:mimeType="text/*",此時(shí)不能使用intent.setData,而要使用intent.setDataAndType();
<intent-filter>
<action android:name="com.babybus_lion.action" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="com.babybus_lion.category" />
<data
android:host="[www.babybus_lion.com](https://link.jianshu.com?t=http://www.babybus_lion.com)"
android:scheme="babybus_lion" android:mimeType="text/*"/>
</intent-filter>
代碼為:
Intent intent = new Intent();
intent.setAction("com.babybus_lion.action");
intent.addCategory("com.babybus_lion.category");
intent.setDataAndType(uri,"text/*");