Android之Intent詳解

目錄

  • 一、Intent概述
  • 二、Activity匹配接收隱式Intent的匹配規則
  • 三、隱式Intent的配置方法
  • 四、常用的Inten隱式設置示例
  • 五、Intent簡單應用示例

一、Intent概述

  1. 定義

Intent被譯作意圖,通過Intent,你的程序可以向Android表達某種請求或者意願,Android會根據意願的內容選擇適當的組件來完成請求。

  1. 顯示Intent與隱式Intent
  • 顯示Intent與隱式Intent
//1.表示顯示Intent,也就是直接指定目標Activity
Intent intent = new Intent();
//1.1 通過ComponentName來指定
ComponentName componentName = new ComponentName("com.sample.demo3", "com.sample.demo3.MainActivity");
intent.setComponent(componentName);
//1.2 通過ClassName來指定
intent.setClassName(this, "com.sample.demo3.MainActivity");
intent.setClass(this, intent.getClass());

startActivity(intent);
//2.表示隱式Intent,也就是不直接指定目標Activity
Intent intent = new Intent();
intent.setAction(Intent.ACTION_NEW);
startActivity(intent);

二、Activity匹配接收隱式Intent的匹配規則

  1. 示例
  • 我們需要在清單文件的中建立Activity和隱式Intent的匹配關係。例如下面是一個入口Activity匹配隱式Intent的示例。
<activity
    android:name=".MainActivity"
    android:label="@string/app_name" >
    //進行匹配規則的制定
    <!-- 這個活動是主條目,應該出現在app啓動器 -->
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />//ACTION_MAIN動作表示這是主入口點,不期望任何intent數據。
        <category android:name="android.intent.category.LAUNCHER" />//CATEGORY_LAUNCHER類別表示該活動的圖標應該放置在系統的應用程序啓動器中。如果元素沒有指定帶有圖標的圖標,那麼系統將使用來自元素的圖標。
    </intent-filter>
</activity>
    <action>
        在name屬性中聲明接收的意圖操作。也就是name值指定了可以接收的Action屬性。
    <data>
        表明接收的數據類型,使用一個或多個屬性指定數據URI的各個方面(scheme, host, port, path)和MIME類型。
    <category>
        在name屬性中聲明接受的intent類別。
  1. Action:指定Activity可以執行的動作

Action標識用來說明這個Activity可以執行哪些動作,Activity在標籤下可以通過來指定action屬性,然後去匹配含有該action屬性的Intent。

  • 一些常用的示例如下
ACTION_CALL activity 啓動一個電話.
ACTION_EDIT activity 顯示用戶編輯的數據.
ACTION_MAIN activity 作爲Task中第一個Activity啓動
ACTION_SYNC activity 同步手機與數據服務器上的數據.
ACTION_BATTERY_LOW broadcast receiver 電池電量過低警告.
ACTION_HEADSET_PLUG broadcast receiver 插拔耳機警告
ACTION_SCREEN_ON broadcast receiver 屏幕變亮警告.
ACTION_TIMEZONE_CHANGED broadcast receiver 改變時區警告.
  • 注意一:一條元素至少應該包含一個,否則任何Intent請求都不能和該匹配;
  • 注意二:如果中沒有包含任何Action類型,那麼無論什麼Intent請求都無法和這條匹配。反之,如果Intent請求中沒有設定Action類型,那麼只要中包含有Action類型,這個Intent請求就將順利地通過的行爲測試。
  1. Category:於指定當前動作(Action)被執行的環境
  • 定義:指定這個activity在哪個環境中才能被激活。不屬於這個環境的,不能被激活。
     CATEGORY_DEFAULT:Android系統中默認的執行方式,按照普通Activity的執行方式執行。表示所有intent都可以激活它 

    CATEGORY_HOME:設置該組件爲Home Activity。

    CATEGORY_PREFERENCE:設置該組件爲Preference。 

    CATEGORY_LAUNCHER:設置該組件爲在當前應用程序啓動器中優先級最高的Activity,通常爲入口ACTION_MAIN配合使用。 

    CATEGORY_BROWSABLE:設置該組件可以使用瀏覽器啓動。表示該activity只能用來瀏覽網頁。 

    CATEGORY_GADGET:設置該組件可以內嵌到另外的Activity中。
  • 注意:如果該activity想要通過隱式intent方式激活,那麼不能沒有任何category設置,至少包含一個android.intent.category.DEFAULT
  1. Data 指定了執行時要操作的數據
  • 目標標籤中包含了以下幾種子元素,他們定義了url的匹配規則:

android:scheme 匹配url中的前綴,除了“http”、“https”、“tel”…之外,我們可以定義自己的前綴
android:host 匹配url中的主機名部分,如“google.com”,如果定義爲“*”則表示任意主機名
android:port 匹配url中的端口
android:path 匹配url中的路徑

<activity android:name=".TargetActivity">
<intent-filter>
	<action android:name="com.scott.intent.action.TARGET"/>
	<category android:name="android.intent.category.DEFAULT"/>
	<data android:scheme="scott" android:host="com.scott.intent.data" android:port="7788" android:path="/target"/>
    //配置接收的數據MIME類型
    <data android:mimeType="application/vnd.google.panorama360+jpg"/>
    <data android:mimeType="image/*"/>
    <data android:mimeType="video/*"/>
    <data android:mimeType="text/plain"/>
</intent-filter>
</activity>

三、隱式Intent的配置方法

  1. 設置Intent的Action屬性
  • 注意:一個activity可以有多個action,只要有一個匹配就可以被啓動。
//1.設置示例一
Intent intent = new Intent("com.scott.intent.action.TARGET");
startActivity(intent);
//2.設置示例二
intent.setAction(Intent.ACTION_VIEW);
intent.setAction(Intent.ACTION_SEND);
  1. 設置Intent的Category屬性
  • 一個intent對象可以有任意個category。intent類定義了許多category常數,這裏就不做演示了。
//1.基本方法
addCategory()方法爲一個intent對象增加一個category,
removeCategory刪除一個category,
getCategories()獲取intent所有的category.

//2.一些添加示例
//目標活動允許web瀏覽器自己啓動,以顯示鏈接引用的數據,如圖像或電子郵件消息。
intent.addCategory(Intent.CATEGORY_BROWSABLE);
//活動是任務的初始活動,列在系統的應用程序啓動程序中。
intent.addCategory(Intent.CATEGORY_LAUNCHER);
  1. 設置Intent的Data屬性

有兩種設置Intent的Data屬性的方式。

  • 方式一:通過Intent的構造函數
//1.方法
public Intent(String action, Uri uri) {
    mAction = action;
    mData = uri;
}
//2.示例
Intent intent = new Intent("com.scott.intent.action.name");
intent.setData(Uri.parse("scheme://host:port/parth"));
startActivity(intent);
  • 方式二:通過setData()方法進行設置
//示例
Intent intent = new Intent("com.scott.intent.action.name");
//要僅設置數據URI,請調用setData()。要僅設置MIME類型,請調用setType()。如果需要,可以使用setDataAndType()顯式地設置。
intent.setData(Uri.parse("scheme://host:port/parth"));
intent.setType("");
intent.setDataAndType();
startActivity(intent);
<activity android:name=".TargetActivity">
	<intent-filter>
		<action android:name="com.scott.intent.action.TARGET"/>
		<category android:name="android.intent.category.DEFAULT"/>
		<data android:scheme="scott" android:host="com.scott.intent.data" android:port="7788" android:path="/target"/>
	</intent-filter>
</activity>
不過有時候對path限定死了也不太好,比如我們有這樣的url:(scott://com.scott.intent.data:7788/target/hello)(scott://com.scott.intent.data:7788/target/hi)

這個時候該怎麼辦呢?我們需要使用另外一個元素:android:pathPrefix,表示路徑前綴。
我們把android:path="/target"修改爲android:pathPrefix="/target",然後就可以滿足以上的要求了。
  1. 設置Intent的Extra屬性

這個參數不參與匹配activity,而僅作爲額外數據傳送到另一個activity中,接收的activity可以將其取出來。這些信息並不是激活這個activity所必須的。也就是說激活某個activity與否只上action、data、catagory有關,與extras無關。而extras用來傳遞附加信息,諸如用戶名,用戶密碼什麼的。

  • 下面直接寫上示例就清楚了
//發送方
Intent intent = new Intent("com.scott.intent.action.TARGET");
Bundle bundle = new Bundle();
bundle.putInt("id", 0);
bundle.putString("name", "scott");
intent.putExtras(bundle);
startActivity(intent);
//接收方
Bundle bundle = intent.getExtras();
int id = bundle.getInt("id");
String name = bundle.getString("name");

四、常用的Inten隱式設置示例

// 調用瀏覽器
Uri webViewUri = Uri.parse("http://blog.csdn.net/zuolongsnail");
Intent intent = new Intent(Intent.ACTION_VIEW, webViewUri);

// 調用地圖
Uri mapUri = Uri.parse("geo:100,100");
Intent intent = new Intent(Intent.ACTION_VIEW, mapUri);

// 播放mp3
Uri playUri = Uri.parse("file:///sdcard/test.mp3");
Intent intent = new Intent(Intent.ACTION_VIEW, playUri);
intent.setDataAndType(playUri, "audio/mp3");

// 調用撥打電話
Uri dialUri = Uri.parse("tel:10086");
Intent intent = new Intent(Intent.ACTION_DIAL, dialUri);
// 直接撥打電話,需要加上權限<uses-permission id="android.permission.CALL_PHONE" />
Uri callUri = Uri.parse("tel:10086");
Intent intent = new Intent(Intent.ACTION_CALL, callUri);

// 調用發郵件(這裏要事先配置好的系統Email,否則是調不出發郵件界面的)
Uri emailUri = Uri.parse("mailto:[email protected]");
Intent intent = new Intent(Intent.ACTION_SENDTO, emailUri);
// 直接發郵件
Intent intent = new Intent(Intent.ACTION_SEND);
String[] tos = { "[email protected]" };
String[] ccs = { "[email protected]" };
intent.putExtra(Intent.EXTRA_EMAIL, tos);
intent.putExtra(Intent.EXTRA_CC, ccs);
intent.putExtra(Intent.EXTRA_TEXT, "the email text");
intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
intent.setType("text/plain");
Intent.createChooser(intent, "Choose Email Client");

// 發短信
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra("sms_body", "the sms text");
intent.setType("vnd.android-dir/mms-sms");
// 直接發短信
Uri smsToUri = Uri.parse("smsto:10086");
Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
intent.putExtra("sms_body", "the sms text");
// 發彩信
Uri mmsUri = Uri.parse("content://media/external/images/media/23");
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra("sms_body", "the sms text");
intent.putExtra(Intent.EXTRA_STREAM, mmsUri);
intent.setType("image/png");

// 卸載應用
Uri uninstallUri = Uri.fromParts("package", "com.app.test", null);
Intent intent = new Intent(Intent.ACTION_DELETE, uninstallUri);
// 安裝應用
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File("/sdcard/test.apk"), "application/vnd.android.package-archive");

// 在Android Market中查找應用
Uri uri = Uri.parse("market://search?q=憤怒的小鳥");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);

五、Intent簡單應用示例

一、使用包含預定義動作的隱式Intent

//1.清單文件配置
<activity
    android:name=".SecondActivity"
    android:label="@string/title_activity_second" >
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>
//2.配置隱式Intent
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
startActivity(intent);

二、使用自定義動作的隱式Intent

//1.在上例的基礎上,更改AndroidManifest.xml,爲SecondActivity自定義一個action name
 <activity
     android:name=".SecondActivity"
     android:label="@string/title_activity_second" >
     <intent-filter>
         <action android:name="test_action" />

         <category android:name="android.intent.category.DEFAULT" />
     </intent-filter>
 </activity>
//2.隱式Intent跳轉,設置Action爲test_action的自定義值
Intent intent = new Intent();
intent.setAction("test_action");
startActivity(intent);

三、使用Intent打開網頁

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.baidu.com"));
startActivity(intent);

四、下載程序的實現

//下載程序的顯示Intent使用
Intent downloadIntent = new Intent(this, DownloadService.class);
downloadIntent.setData(Uri.parse(fileUrl));// The fileUrl is a string URL, such as "http://www.example.com/image.png"
startService(downloadIntent);

五、共享數據,並且可以指定我共享數據的類型

Intent sendIntent = new Intent();
//與其他人共享內容
sendIntent.setAction(Intent.ACTION_SEND);
//添加額外的內容來指定要共享的內容
sendIntent.putExtra(Intent.EXTRA_TEXT, "處理我的Intent指定數據的Activity打開了");
//指定我發送的數據內容的數據格式
sendIntent.setType("text/plain");
//用於驗證是否有應用可以響應Intent請求,如果沒有就不打開應用
if (sendIntent.resolveActivity(getPackageManager()) != null) {
    startActivity(sendIntent);
}

六、Intent使用串燒

Intent intent = new Intent();
switch (Integer.parseInt(editText.getText().toString())) {
    case 1:
        //在本Activity中打開聯繫人名稱爲1的面板,可以進行編輯
        intent.setAction(Intent.ACTION_VIEW);
//                    intent.setData(Uri.parse("https://www.baidu.com"));
//                    intent.setData(Uri.parse("content://contacts/people/1"));
        intent.setData(Uri.parse("https://www.csdn.net/"));
        break;
    case 2:
        //顯示電話撥號與人填寫
        intent.setAction(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("content://contacts/people/1"));
        break;
    case 3:
        //編輯標識符爲“1”的人的信息。
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("content://contacts/people/1"));
        break;
    case 4:
        //顯示電話撥號與給定的數字填寫
        intent.setAction(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:123"));
        break;
    case 5:
        //編輯標識符爲“1”的人的信息。
        intent.setAction(Intent.ACTION_EDIT);
        intent.setData(Uri.parse("content://contacts/people/1"));
        break;
    case 6:
        //顯示用戶可以瀏覽的人員列表。
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("content://contacts/people/"));
        break;
    /************************Category:********************************/
    case 8:
        //它應該作爲頂級應用程序出現在啓動程序中,其實就是程序啓動入口
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        break;
    case 9:
        //它應該包含在用戶可以對數據執行的可選操作列表中
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
        break;
    /************************其他補充:********************************/
    case 10:
        //啓動主屏幕
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        break;
    case 11:
        //顯示人們的電話號碼列表
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.setType("item/phone");//vnd.android.cursor.item/phone
        break;
    case 12:
        //顯示所有用戶數據
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        break;
    case 13:
        //顯示所有notes的列表。“記事本/便箋簿” 目前無效
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("content://com.google.provider.NotePad/notes"));
        break;
    default:
        //保持每次重新開啓app之後進入的主界面都是固定的頁面(默認情況下會在每次app重啓之後顯示關閉之前的頁面)
        intent.setFlags(intent.FLAG_ACTIVITY_NO_HISTORY);
        break;
}
startActivity(intent);

結語

如果大家我的文章講的不夠好,大家可以參考大神的文章:https://blog.csdn.net/harvic880925/article/details/38399723

直到這裏,差不多Intent的使用方法已經介紹完畢了,他的作用就是發送信息。可以指定固定的接受者或者可以設置匹配規則,這個就是Intent的使用本質了。如果大家喜歡的話,希望…

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章