1.顯式Intent
Intent有多個構造函數的重載,其中一個是:
Intent(Context packageContext,Class<?> cls).
這個構造函數接收兩個參數,第一個參數Context要求提供一個啓動活動的上下文,第二個參數Class則是指定想要啓動的目標活動,通過這個構造函數就可以構建出Intent的意圖.
Intent的使用:
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
startActivity(intent);
2.隱式Intent
相對於顯式Intent,隱式Intent含蓄了許多,它並不明確的指出我們想要啓動那個活動,而是指定了一系列的更爲抽象的action或category等信息,然後由系統分析這個Intent,並幫我們找到合適的活動去啓動.
//通過在<activity>標籤下配置<intent-filter>的內容,可以指定當前活動能夠響應的action和category,打開AndroidManifest.xml,添加如下代碼
<activity android:name = ".SecondActivity">
<intent-filter>
<action android:name="com.example.activitytest.ACTION_START"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
//在<action>標籤中我們指明瞭當前活動可以響應com.example.actvitytest.ACTION_START這個action,而<category>標籤則包含了一些附加信息,更精確的指明瞭當前活動能夠響應的Intent中還可能帶有的category.只有<action>和<category>中的內容同時能夠匹配上Intent中指定的action和category時,這個活動才能響應該Intent
Intent的使用:
Intent intent = new Intent("com.example.activitytest.ACTION_START");
startActivity(intent);
因爲android.intent.category.DEFAULT是一種默認的category,在調用startActivity()的時候會自動將這個category添加到Intent中.
每個Intent只能有一個action,但可以指定多個category.
//增加一個category
Intent intent = new Intent("com.example.activitytest.ACTION_START");
intent.addCategory("com.example.activitytest.MY_CATEGORY");
startActivity(intent);
//我們必須在<intent-filter>添加一個category的聲明
<activity android:name = ".SecondActivity">
<intent-filter>
<action android:name="com.example.activitytest.ACTION_START"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="com.example.activitytest.MY_CATEGORY"/>
</intent-filter>
</activity>
3.更多隱式Intent的用法
//用瀏覽器打開網頁
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.baidu.com"));
startActivity(intent);
//與此對應,我們還可以在<intent-filter>標籤中配置一個<data>標籤,用於更精確的指定當前活動能夠響應什麼類型的數據
//android:scheme.用於指定數據的協議部分,如上面的http部分
//android:host.用於指定數據的主機名部分,如上面的www.baidu.com部分
//android:port.用於指定數據的端口部分,一般緊隨在主機名之後
//android:path.用於指定主機名和端口之後的部分,如一段網址中跟在域名之後的內容
//android:mimeType.用於指定可以處理的數據類型,允許使用通配符的方式進行指定
例如:
<activity android:name = ".SecondActivity">
<intent-filter>
<action android:name="com.example.activitytest.ACTION_START"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="http"/>
</intent-filter>
</activity>
//撥打電話
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:10086"));
startActivity(intent);