### 一. Intent的介紹
- Android中提供了Intent機制來協助應用間的交互與通訊,或者采用更準確的說法是,Intent不僅可用于應用程序之間,也可用于應用程序內部的activity, service和broadcast receiver之間的交互。
- Intent是一種運行時綁定(runtime binding)機制,它能在程序運行的過程中連接兩個不同的組件。通過Intent,你的程序可以向Android表達某種請求或者意愿,Android會根據意愿的內容選擇適當的組件來響應。
Intent的中文意思是“意圖,意向”,在Android中提供了Intent機制來協助應用間的交互與通訊,Intent負責對應用中一次操作的動作、動作涉及數據、附加數據進行描述,Android則根據此Intent的描述,負責找到對應的組件,將 Intent傳遞給調用的組件,并完成組件的調用。Intent不僅可用于應用程序之間,也可用于應用程序內部的Activity/Service之間的交互。因此,可以將Intent理解為不同組件之間通信的“媒介”專門提供組件互相調用的相關信息,起著一個媒體中介的作用,專門提供組件互相調用的相關信息,實現調用者與被調用者之間的解耦。
Intent 是一個將要執行的動作的抽象的描述,一般來說是作為參數來使用,由Intent來協助完成android各個組件之間的通訊。比如說調用 startActivity()來啟動一個activity,或者由broadcaseIntent()來傳遞給所有感興趣的 BroadcaseReceiver, 再或者由startService()/bindservice()來啟動一個后臺的service。所以可以看出來,intent主要是用來啟動其他的 activity 或者service,所以可以將intent理解成activity之間的粘合劑。
### 主要用途
Intent是一種消息傳遞機制,它可以在應用程序內使用,也可以在應用程序間使用,主要用途分為:
1.使用類名顯示的啟動一個特定的Activity或Service
2.啟動Activity或Service來執行一個動作的Intent,通常需要使用特定的數據,或者對特定的數據執行動作
3.廣播某個事件已經發生
activity、service和broadcast receiver之間是通過Intent進行通信的,而另外一個組件Content Provider本身就是一種通信機制,不需要通過Intent。我們來看下面這個圖就知道了:

如果Activity1需要和Activity2進行聯系,二者不需要直接聯系,而是通過Intent作為橋梁。通俗來講,Intnet類似于中介、媒婆的角色。
Intent最常見的一個用法是顯示的(通過指定要裝載的類)或隱式的(通過請求對一條數據執行某個動作)啟動新的activity,在后一種情況下,動作不一定由調用應用程序中的Activty執行。
Intent也可以在系統范圍內發送廣播消息。應用程序可以注冊一個Broadcast Receiver來監聽相應這些廣播的Intent。Android就是通過廣播Intent來公布系統事件,比如網絡連接狀態或者電池電量的改變。
### 二. Inten啟動組件的方法
Intent可以啟動一個Activity,也可以啟動一個Service,還可以發起一個廣播Broadcasts。具體方法如下:
#### 對于向這三種組件發送intent有不同的機制:
- 使用Context.startActivity() 或 Activity.startActivityForResult(),傳入一個intent來啟動一個activity。使用 Activity.setResult(),傳入一個intent來從activity中返回結果。
- 將intent對象傳給Context.startService()來啟動一個service或者傳消息給一個運行的service。將intent對象傳給 Context.bindService()來綁定一個service。
- 將intent對象傳給 Context.sendBroadcast(),Context.sendOrderedBroadcast(),或者Context.sendStickyBroadcast()等廣播方法,則它們被傳給 broadcast receiver。
<table align="center" width="400" border="1" cellpadding="2" cellspacing="0"><tbody><tr><td valign="top" width="194"><p align="center">組件名稱</p></td><td valign="top" width="204"><p align="center">方法名稱</p></td></tr><tr><td valign="top" width="191">Activity</td><td valign="top" width="207"><p>startActvity( ) </p><p>startActivityForResult( )</p></td></tr><tr><td valign="top" width="189">Service</td><td valign="top" width="209"><p>startService( ) </p><p>bindService( )</p></td></tr><tr><td valign="top" width="188">Broadcasts</td><td valign="top" width="211"><p>sendBroadcasts( ) </p><p>sendOrderedBroadcasts( ) </p><p>sendStickyBroadcasts( )</p></td></tr></tbody></table>
### 三. Intent的構成
Intent由以下各個組成部分:
- component(組件):目的組件
- action(動作):用來表現意圖的行動
- category(類別):用來表現動作的類別
- data(數據):表示與動作要操縱的數據
- type(數據類型):對于data范例的描寫
- extras(擴展信息):擴展信息
- Flags(標志位):期望這個意圖的運行模式
#### 1、component(組件):目的組件
指定Intent的的目標組件的類名稱。通常 Android會根據Intent 中包含的其它屬性的信息,比如action、data/type、category進行查找,最終找到一個與之匹配的目標組件。但是,如果 component這個屬性有指定的話,將直接使用它指定的組件,而不再執行上述查找過程。指定了這個屬性以后,Intent的其它所有屬性都是可選的。
例如,啟動第二個Activity時,我們可以這樣來寫:
~~~
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//創建一個意圖對象
Intent intent = new Intent();
//創建組件,通過組件來響應
ComponentName component = new ComponentName(MainActivity.this, SecondActivity.class);
intent.setComponent(component);
startActivity(intent);
}
});
~~~
如果寫的簡單一點,監聽事件onClick()方法里可以這樣寫:
~~~
Intent intent = new Intent();
//setClass函數的第一個參數是一個Context對象
//Context是一個類,Activity是Context類的子類,也就是說,所有的Activity對象,都可以向上轉型為Context對象
//setClass函數的第二個參數是一個Class對象,在當前場景下,應該傳入需要被啟動的Activity類的class對象
intent.setClass(MainActivity.this, SecondActivity.class);
startActivity(intent);
~~~
再簡單一點,可以這樣寫:(當然,也是最常見的寫法)
~~~
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
~~~
#### 2、Action(動作):用來表現意圖的行動
當日常生活中,描述一個意愿或愿望的時候,總是有一個動詞在其中。比如:我想“做”三個俯臥撐;我要“寫”一封情書,等等。在Intent中,Action就是描述做、寫等動作的,當你指明了一個Action,執行者就會依照這個動作的指示,接受相關輸入,表現對應行為,產生符合的輸出。在Intent類中,定義了一批量的動作,比如ACTION_VIEW,ACTION_PICK等, 基本涵蓋了常用動作。加的動作越多,越精確。
#### 標準的Activity Actions
ACTION_MAIN???????????????????????????? 作為一個主要的進入口,而并不期望去接受數據
ACTION_VIEW???????????????????????????? 向用戶去顯示數據
ACTION_ATTACH_DATA?????????????? 用于指定一些數據應該附屬于一些其他的地方,例如,圖片數據應該附屬于聯系人
ACTION_EDIT????????????????????????????? 訪問已給的數據,提供明確的可編輯
ACTION_PICK????????????????????????????? 從數據中選擇一個子項目,并返回你所選中的項目
ACTION_CHOOSER????????????????????? 顯示一個activity選擇器,允許用戶在進程之前選擇他們想要的
ACTION_GET_CONTENT?????????????? 允許用戶選擇特殊種類的數據,并返回(特殊種類的數據:照一張相片或錄一段音)
ACTION_DIAL?????????????????????????????? 撥打一個指定的號碼,顯示一個帶有號碼的用戶界面,允許用戶去啟動呼叫
ACTION_CALL????????????????????????????? 根據指定的數據執行一次呼叫
(ACTION_CALL在應用中啟動一次呼叫有缺陷,多數應用ACTION_DIAL,ACTION_CALL不能用在緊急呼叫上,緊急呼叫可以用ACTION_DIAL來實現)
ACTION_SEND???????????????????????????? 傳遞數據,被傳送的數據沒有指定,接收的action請求用戶發數據
ACTION_SENDTO???????????????????????? 發送一個信息到指定的某人
ACTION_ANSWER??????????????????????? 處理一個打進電話呼叫
ACTION_INSERT????????????????????????? 插入一條空項目到已給的容器
ACTION_DELETE????????????????????????? 從容器中刪除已給的數據
ACTION_RUN?????????????????????????????? 運行數據,無論怎么
ACTION_SYNC???????????????????????????? 同步執行一個數據
ACTION_PICK_ACTIVITY????????????? 為已知的Intent選擇一個Activity,返回別選中的類
ACTION_SEARCH???????????????????????? 執行一次搜索
ACTION_WEB_SEARCH??????????????? 執行一次web搜索
ACTION_FACTORY_TEST????????????? 工場測試的主要進入點,
#### 標準的廣播Actions
ACTION_TIME_TICK?????????????????? 當前時間改變,每分鐘都發送,不能通過組件聲明來接收,只有通過Context.registerReceiver()方法來注冊
ACTION_TIME_CHANGED??????????? 時間被設置
ACTION_TIMEZONE_CHANGED?? 時間區改變
ACTION_BOOT_COMPLETED?????? 系統完成啟動后,一次廣播
ACTION_PACKAGE_ADDED???????? 一個新應用包已經安裝在設備上,數據包括包名(最新安裝的包程序不能接收到這個廣播)
ACTION_PACKAGE_CHANGED??? 一個已存在的應用程序包已經改變,包括包名
ACTION_PACKAGE_REMOVED?? 一個已存在的應用程序包已經從設備上移除,包括包名(正在被安裝的包程序不能接收到這個廣播)
ACTION_PACKAGE_RESTARTED 用戶重新開始一個包,包的所有進程將被殺死,所有與其聯系的運行時間狀態應該被移除,包括包名(重新開始包程序不能接收到這個廣播)
ACTION_PACKAGE_DATA_CLEARED 用戶已經清楚一個包的數據,包括包名(清除包程序不能接收到這個廣播)
ACTION_BATTERY_CHANGED 電池的充電狀態、電荷級別改變,不能通過組建聲明接收這個廣播,只有通過Context.registerReceiver()注冊
ACTION_UID_REMOVED 一個用戶ID已經從系統中移除
#### 3、category(類別):用來表現動作的類別
Intent中的Category屬性是一個執行動作Action的附加信息。比如:CATEGORY_HOME則表示放回到Home界面,ALTERNATIVE_CATEGORY表示當前的Intent是一系列的可選動作中的一個。
指定Action范圍,這個選項指定了將要執行的這個action的其他一些額外的約束。有時通過Action,配合Data 或Type,很多時候可以準確的表達出一個完整的意圖了,但也會需要加一些約束在里面才能夠更精準。比如,如果你雖然很喜歡做俯臥撐,但一次做三個還只是在特殊的時候才會發生,那么你可能表達說:每次吃撐了的時候 ,我都想做三個俯臥撐。吃撐了,這就對應著Intent的Category的范疇,它給所發生的意圖附加一個約束。在Android中,一個實例是:所有應用的主Activity(單獨啟動時候,第一個運行的那個Activity...),都需要一個Category為 CATEGORY_LAUNCHER,Action為ACTION_MAIN的Intent。
在自定義動作時,使用activity組件時,必須添加一個默認的類別
具體的實現為:
~~~
<intent-filter>
<action android:name="com.example.action.MY_ACTION"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
~~~
如果有多個組件被匹配成功,就會以對話框列表的方式讓用戶進行選擇。
每個Intent中只能指定一個action,但卻能指定多個category;類別越多,動作越具體,意圖越明確(類似于相親時,給對方提了很多要求)。
自定義類別: 在Intent添加類別可以添加多個類別,那就要求被匹配的組件必須同時滿足這多個類別,才能匹配成功。操作Activity的時候,如果沒有類別,須加上默認類別
| Constant | Meaning |
|-----|-----|
| `CATEGORY_BROWSABLE` | The target activity can be safely invoked by the browser to display data referenced by a link — for example, an image or an e-mail message. |
| `CATEGORY_GADGET` | The activity can be embedded inside of another activity that hosts gadgets. |
| `CATEGORY_HOME` | The activity displays the home screen, the first screen the user sees when the device is turned on or when the HOME key is pressed. |
| `CATEGORY_LAUNCHER` | The activity can be the initial activity of a task and is listed in the top-level application launcher. |
| `CATEGORY_PREFERENCE` | The target activity is a preference panel. |
#### 4、data(數據):表示與動作要操縱的數據 =
- Data屬性是Android要訪問的數據,和action和Category聲明方式相同,也是在<intent-filter>中。
- 多個組件匹配成功顯示優先級高的; 相同顯示列表。
Data是用一個uri對象來表示的,uri代表數據的地址,屬于一種標識符。通常情況下,我們使用action+data屬性的組合來描述一個意圖:做什么
使用隱式Intent,我們不僅可以啟動自己程序內的活動,還可以啟動其他程序的活動,這使得Android多個應用程序之間的功能共享成為了可能。比如應用程序中需要展示一個網頁,沒有必要自己去實現一個瀏覽器(事實上也不太可能),而是只需要條用系統的瀏覽器來打開這個網頁就行了。
- 當Intent匹配成功的組件有多個時,顯示優先級高的組件,如果優先級相同,顯示列表讓用戶自己選擇
- 優先級從-1000至1000,并且其中一個必須為負的才有效
注:系統默認的瀏覽器并沒有做出優先級聲明,其優先級默認為正數。
Data屬性的聲明中要指定訪問數據的Uri和MIME類型。可以在<data>元素中通過一些屬性來設置:
android:scheme、android:path、 android:port、android:mimeType、android:host等,通過這些屬性來對應一個典型的Uri格式 scheme://host:port/path。例如:http://www.google.com。
#### 5、type(數據類型):對于data范例的描寫
如果Intent對象中既包含Uri又包含Type,那么,在<intent-filter>中也必須二者都包含才能通過測試。
Type屬性用于明確指定Data屬性的數據類型或MIME類型,但是通常來說,當Intent不指定Data屬性時,Type屬性才會起作用,否則Android系統將會根據Data屬性值來分析數據的類型,所以無需指定Type屬性。
data和type屬性一般只需要一個,通過setData方法會把type屬性設置為null,相反設置setType方法會把data設置為null,如果想要兩個屬性同時設置,要使用Intent.setDataAndType()方法。
#### 6、extras(擴展信息):擴展信息
是其它所有附加信息的集合。使用extras可以為組件提供擴展信息,比如,如果要執行“發送電子郵件”這個動作,可以將電子郵件的標題、正文等保存在extras里,傳給電子郵件發送組件。
#### 7、Flags(標志位):期望這個意圖的運行模式
一個程序啟動后系統會為這個程序分配一個task供其使用,另外同一個task里面可以擁有不同應用程序的activity。那么,同一個程序能不能擁有多個task?這就涉及到加載activity的啟動模式,這個需要單獨講一下。能識別,有輸入,整個Intent基本就完整了,但還有一些附件的指令,需要放在Flags中帶過去。顧名思義,Flags是一個整形數,有一些列的標志 位構成,這些標志,是用來指明運行模式的。比如,你期望這個意圖的執行者,和你運行在兩個完全不同的任務中(或說進程也無妨吧...),就需要設置**FLAG_ACTIVITY_NEW_TASK**的標志位。
注:android中一組邏輯上在一起的activity被叫做task,自己認為可以理解成一個activity堆棧。
### Intent 的解析機制
理解Intent的關鍵之一是理解清楚Intent的兩種基本用法:一種是**顯式的Intent**,即在構造Intent對象時就指定接收者;另一種是**隱式的Intent**,即Intent的發送者在構造Intent對象時,并不知道也不關心接收者是誰,有利于降低發送者和接收者之間的耦合。官方建議使用隱式Intent。上述屬性中,component屬性為直接類型,其他均為間接類型。
對于顯式Intent,Android不需要去做解析,因為目標組件已經很明確,Android需要解析的是那些隱式Intent,通過解析,將 Intent映射給可以處理此Intent的Activity、IntentReceiver或Service。
相比與顯式Intent,隱式Intnet則含蓄了許多,它并不明確指出我們想要啟動哪一個活動,而是指定一系列更為抽象的action和category等信息,然后交由系統去分析這個Intent,并幫我們找出合適的活動去啟動。
Activity 中 Intent Filter 的匹配過程 :

Intent 解析機制主要是通過查找已注冊在AndroidManifest.xml中的所有IntentFilter及其中定義的Intent,最終找到匹配的 Intent。在這個解析過程中,Android是通過Intent的action、type、category這三個屬性來進行判斷的,判斷方法如下:
- 如果Intent指明定了action,則目標組件的IntentFilter的action列表中就必須包含有這個action,否則不能匹配;
- 如果Intent沒有提供type,系統將從data中得到數據類型。和action一樣,目標組件的數據類型列表中必須包含Intent的數據類型,否則不能匹配。
- 如果Intent中的數據不是content: 類型的URI,而且Intent也沒有明確指定它的type,將根據Intent中數據的scheme (比如 http: 或者[mailto](http://www.androidcn.net/wiki/index.php/Reference/android/content/mailto):) 進行匹配。同上,Intent 的scheme必須出現在目標組件的scheme列表中。
- 如果Intent指定了一個或多個category,這些類別必須**全部**出現在組建的類別列表中。比如Intent中包含了兩個類別:LAUNCHER_CATEGORY 和 ALTERNATIVE_CATEGORY,解析得到的目標組件必須至少包含這兩個類別。
**Intent-Filter的定義**
一些屬性設置的例子:
~~~
<action android:name="com.example.project.SHOW_CURRENT" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="video/mpeg" android:scheme="http" . . . />
<data android:mimeType="image/*" />
<data android:scheme="http" android:type="video/*" />
~~~
完整的實例
~~~
<activity android:name="NotesList" android:label="@string/title_notes_list">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.EDIT" />
<action android:name="android.intent.action.PICK" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="vnd.android.cursor.dir/vnd.google.note" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.GET_CONTENT" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="vnd.android.cursor.item/vnd.google.note" />
</intent-filter>
</activity>
~~~
### Intent的構造函數
公共構造函數:
1、Intent() 空構造函數
2、Intent(Intent o) 拷貝構造函數
3、Intent(String action) 指定action類型的構造函數
4、Intent(String action, Uri uri) 指定Action類型和Uri的構造函數,URI主要是結合程序之間的數據共享ContentProvider
5、Intent(Context packageContext, Class<?> cls) 傳入組件的構造函數,也就是上文提到的
6、Intent(String action, Uri uri, Context packageContext, Class<?> cls) 前兩種結合體
Intent有六種構造函數,3、4、5是最常用的,并不是其他沒用!
Intent(String action, Uri uri) 的action就是對應在AndroidMainfest.xml中的action節點的name屬性值。在Intent類中定義了很多的Action和Category常量。
**示例代碼二:**
~~~
Intent intent = new Intent(Intent.ACTION_EDIT, null);
startActivity(intent);
~~~
示例代碼二是用了第四種構造函數,只是uri參數為null。執行此代碼的時候,系統就會在程序主配置文件AndroidMainfest.xml中尋找
<action android:name="android.intent.action.EDIT" />對應的Activity,如果對應為多個activity具有<action android:name="android.intent.action.EDIT" />此時就會彈出一個dailog選擇Activity。
如果是用示例代碼一那種方式進行發送則不會有這種情況。
**利用Intent在Activity之間傳遞數據**
在Main中執行如下代碼:
~~~
Bundle bundle = new Bundle();
bundle.putStringArray("NAMEARR", nameArr);
Intent intent = new Intent(Main.this, CountList.class);
intent.putExtras(bundle);
startActivity(intent);
~~~
在CountList中,代碼如下:
~~~
Bundle bundle = this.getIntent().getExtras();
String[] arrName = bundle.getStringArray("NAMEARR");
~~~
以上代碼就實現了Activity之間的數據傳遞!
###總結說明
這篇文章是我剛開始學習Android時看到的,當時理解的不是很深入,現在再回頭看這篇文章總結的很詳細,在這里與大家分享。
1,調用web瀏覽器
~~~
<pre name="code" class="java">Uri myBlogUri = Uri.parse("http://kuikui.javaeye.com");
returnIt = new Intent(Intent.ACTION_VIEW, myBlogUri);
~~~
~~~
~~~
2,地圖
~~~
Uri mapUri = Uri.parse("geo:38.899533,-77.036476");
returnIt = new Intent(Intent.ACTION_VIEW, mapUri);
~~~
3,調撥打電話界面
~~~
Uri telUri = Uri.parse("tel:100861");
returnIt = new Intent(Intent.ACTION_DIAL, telUri);
~~~
4,直接撥打電話
~~~
Uri callUri = Uri.parse("tel:100861");
returnIt = new Intent(Intent.ACTION_CALL, callUri);
~~~
5,卸載
~~~
Uri uninstallUri = Uri.fromParts("package", "xxx", null);
returnIt = new Intent(Intent.ACTION_DELETE, uninstallUri);
~~~
6,安裝
~~~
Uri installUri = Uri.fromParts("package", "xxx", null);
returnIt = new Intent(Intent.ACTION_PACKAGE_ADDED, installUri);
~~~
7,播放
~~~
Uri playUri = Uri.parse("file:///sdcard/download/everything.mp3");
returnIt = new Intent(Intent.ACTION_VIEW, playUri);
~~~
8,調用發郵件
~~~
Uri emailUri = Uri.parse("mailto:shenrenkui@gmail.com");
returnIt = new Intent(Intent.ACTION_SENDTO, emailUri);
~~~
9,發郵件
~~~
returnIt = new Intent(Intent.ACTION_SEND);
String[] tos = { "shenrenkui@gmail.com" };
String[] ccs = { "shenrenkui@gmail.com" };
returnIt.putExtra(Intent.EXTRA_EMAIL, tos);
returnIt.putExtra(Intent.EXTRA_CC, ccs);
returnIt.putExtra(Intent.EXTRA_TEXT, "body");
returnIt.putExtra(Intent.EXTRA_SUBJECT, "subject");
returnIt.setType("message/rfc882");
Intent.createChooser(returnIt, "Choose Email Client");
~~~
10,發短信
~~~
Uri smsUri = Uri.parse("tel:100861");
returnIt = new Intent(Intent.ACTION_VIEW, smsUri);
returnIt.putExtra("sms_body", "shenrenkui");
returnIt.setType("vnd.android-dir/mms-sms");
~~~
11,直接發郵件
~~~
Uri smsToUri = Uri.parse("smsto://100861");
returnIt = new Intent(Intent.ACTION_SENDTO, smsToUri);
returnIt.putExtra("sms_body", "shenrenkui");
~~~
12,發彩信
~~~
Uri mmsUri = Uri.parse("content://media/external/images/media/23");
returnIt = new Intent(Intent.ACTION_SEND);
returnIt.putExtra("sms_body", "shenrenkui");
returnIt.putExtra(Intent.EXTRA_STREAM, mmsUri);
returnIt.setType("image/png");
~~~
用獲取到的Intent直接調用startActivity(returnIt)就ok了。
###Intent用法實例
#### 1、打開指定網頁:(直接復制的上面的代碼)
MainActivity.java中,監聽器部分的核心代碼如下:
~~~
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.baidu.com"));
startActivity(intent);
}
});
~~~
第4行代碼:指定了Intent的action是 **Intent.ACTION_VIEW**,表示查看的意思,這是一個Android系統內置的動作;
第5行代碼:通過Uri.parse()方法,將一個網址字符串解析成一個Uri對象,再調用intent的setData()方法將這個Uri對象傳遞進去。
#### 2、打電話:
【方式一】打開撥打電話的界面:
~~~
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:10086"));
startActivity(intent);
~~~
運行程序后,點擊按鈕,顯示如下界面:

【方式二】直接撥打電話:
~~~
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:10086"));
startActivity(intent);
~~~
要使用這個功能必須在配置文件中加入權限:(加一行代碼)
~~~
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.CALL_PHONE"/>
~~~
#### 3、發送短信:
【方式一】打開發送短信的界面:action+type
~~~
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("vnd.android-dir/mms-sms");
intent.putExtra("sms_body", "具體短信內容"); //"sms_body"為固定內容
startActivity(intent);
~~~
【方式二】打開發短信的界面(同時指定電話號碼):action+data
~~~
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("smsto:18780260012"));
intent.putExtra("sms_body", "具體短信內容"); //"sms_body"為固定內容
startActivity(intent);
~~~
#### 4、播放指定路徑音樂:action+data+type
~~~
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse("file:///storage/sdcard0/平凡之路.mp3"); ////路徑也可以寫成:"/storage/sdcard0/平凡之路.mp3"
intent.setDataAndType(uri, "audio/mp3"); //方法:Intent android.content.Intent.setDataAndType(Uri data, String type)
startActivity(intent);
~~~
####5、卸載程序:action+data(例如點擊按鈕,卸載某個應用程序,根據包名來識別)
注:無論是安裝還是卸載,應用程序是根據包名package來識別的。
~~~
Intent intent = new Intent(Intent.ACTION_DELETE);
Uri data = Uri.parse("package:com.example.smyh006intent01");
intent.setData(data);
startActivity(intent);
~~~
#### 6、安裝程序:action+data+type
~~~
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.fromFile(new File("/storage/sdcard0/AndroidTest/smyh006_Intent01.apk")); //路徑不能寫成:"file:///storage/sdcard0/···"
intent.setDataAndType(data, "application/vnd.android.package-archive"); //Type的字符串為固定內容
startActivity(intent);
~~~
注:第2行的路徑不能寫成:"file:///storage/sdcard0/···",不然報錯如下:

綜上所述,完整版代碼如下:
~~~
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1_browsePage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="browsePageClick"
android:text="打開指定網頁"/>
<Button
android:id="@+id/button2_openDialPage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="openDialPageClick"
android:text="打開撥號面板"/>
<Button
android:id="@+id/button3_dialPhone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="dialPhoneClick"
android:text="直接撥打指定號碼"/>
<Button
android:id="@+id/button4_openMsgPage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="openMsgPageClick"
android:text="打開發短信的界面"/>
<Button
android:id="@+id/button5_sendMsg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="sendMsgClick"
android:text="給指定的人發短信"/>
<Button
android:id="@+id/button6_playMusic"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="playMusicClick"
android:text="播放指定路徑音樂"/>
<Button
android:id="@+id/button7_uninstall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="uninstallClick"
android:text="卸載程序"/>
<Button
android:id="@+id/button8_install"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="installClick"
android:text="安裝程序"/>
</LinearLayout>
~~~
MainActivity.java代碼如下:
~~~
package com.example.m06intent01;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//打開指定網頁
public void browsePageClick(View view){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.baidu.com/"));
startActivity(intent);
}
//打開撥號面板
public void openDialPageClick(View view){
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:10086"));
startActivity(intent);
}
//直接撥打指定號碼
public void dialPhoneClick(View view){
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:10086"));
startActivity(intent);
}
//打開發短信的界面:action+type
public void openMsgPageClick(View view){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("vnd.android-dir/mms-sms");
intent.putExtra("sms_body", "具體短信內容"); //"sms_body"為固定內容
startActivity(intent);
}
//打開發短信的界面(指定電話號碼):action+data
public void sendMsgClick(View view){
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("smsto:18780260012"));
intent.putExtra("sms_body", "具體短信內容"); //"sms_body"為固定內容
startActivity(intent);
}
//播放指定路徑音樂
public void playMusicClick(View view){
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse("file:///storage/sdcard0/平凡之路.mp3"); //路徑也可以寫成:"/storage/sdcard0/平凡之路.mp3"
intent.setDataAndType(uri, "audio/mp3"); //方法:Intent android.content.Intent.setDataAndType(Uri data, String type)
startActivity(intent);
}
//卸載某個應用程序,根據包名來識別
public void uninstallClick(View view){
Intent intent = new Intent(Intent.ACTION_DELETE);
Uri data = Uri.parse("package:com.example.smyh006intent01");
intent.setData(data);
startActivity(intent);
}
//安裝某個應用程序,根據apk的文件名來識別
public void installClick(View view){
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.fromFile(new File("/storage/sdcard0/AndroidTest/smyh006_Intent01.apk")); //路徑不能寫成:"file:///storage/sdcard0/···"
intent.setDataAndType(data, "application/vnd.android.package-archive"); //Type的字符串為固定內容
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
~~~
**1.無參數Activity跳轉**
~~~
Intent it = new Intent(Activity.Main.this, Activity2.class);
startActivity(it);
~~~
**2.向下一個Activity傳遞數據(使用Bundle和Intent.putExtras)**
~~~
Intent it = new Intent(Activity.Main.this, Activity2.class);
Bundle bundle=new Bundle();
bundle.putString("name", "This is from MainActivity!");
it.putExtras(bundle); // it.putExtra(“test”, "shuju”);
startActivity(it); // startActivityForResult(it,REQUEST_CODE);
~~~
對于數據的獲取可以采用:
~~~
Bundle bundle=getIntent().getExtras();
String name=bundle.getString("name");
~~~
**3.向上一個Activity返回結果(使用setResult,針對startActivityForResult(it,REQUEST_CODE)啟動的Activity)**
~~~
Intent intent=getIntent();
Bundle bundle2=new Bundle();
bundle2.putString("name", "This is from ShowMsg!");
intent.putExtras(bundle2);
setResult(RESULT_OK, intent);
~~~
**4.回調上一個Activity的結果處理函數(onActivityResult)**
~~~
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==REQUEST_CODE){
if(resultCode==RESULT_CANCELED)
setTitle("cancle");
else if (resultCode==RESULT_OK) {
String temp=null;
Bundle bundle=data.getExtras();
if(bundle!=null) temp=bundle.getString("name");
setTitle(temp);
}
}
}
~~~
運行后,主界面如下:

**下面是轉載來的其他的一些Intent用法實例(轉自javaeye)**
###顯示網頁
~~~
Uri uri = Uri.parse("http://google.com");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
~~~
### 顯示地圖
~~~
Uri uri = Uri.parse("geo:38.899533,-77.036476");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
//其他 geo URI 範例
//geo:latitude,longitude
//geo:latitude,longitude?z=zoom
//geo:0,0?q=my+street+address
//geo:0,0?q=business+near+city
//google.streetview:cbll=lat,lng&cbp=1,yaw,,pitch,zoom&mz=mapZoom
~~~
### 路徑規劃
~~~
Uri uri = Uri.parse("http://maps.google.com/maps?f=d&saddr=startLat%20startLng&daddr=endLat%20endLng&hl=en");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
//where startLat, startLng, endLat, endLng are a long with 6 decimals like: 50.123456
~~~
### 打電話
~~~
//叫出撥號程序
Uri uri = Uri.parse("tel:0800000123");
Intent it = new Intent(Intent.ACTION_DIAL, uri);
startActivity(it);
//直接打電話出去
Uri uri = Uri.parse("tel:0800000123");
Intent it = new Intent(Intent.ACTION_CALL, uri);
startActivity(it);
//用這個,要在 AndroidManifest.xml 中,加上
//<uses-permission id="android.permission.CALL_PHONE" />
~~~
### 傳送SMS/MMS
~~~
//調用短信程序
Intent it = new Intent(Intent.ACTION_VIEW, uri);
it.putExtra("sms_body", "The SMS text");
it.setType("vnd.android-dir/mms-sms");
startActivity(it);
//傳送消息
Uri uri = Uri.parse("smsto://0800000123");
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
it.putExtra("sms_body", "The SMS text");
startActivity(it);
//傳送 MMS
Uri uri = Uri.parse("content://media/external/images/media/23");
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra("sms_body", "some text");
it.putExtra(Intent.EXTRA_STREAM, uri);
it.setType("image/png");
startActivity(it);
~~~
### 傳送 Email
~~~
Uri uri = Uri.parse("mailto:xxx@abc.com");
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
startActivity(it);
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_EMAIL, "me@abc.com");
it.putExtra(Intent.EXTRA_TEXT, "The email body text");
it.setType("text/plain");
startActivity(Intent.createChooser(it, "Choose Email Client"));
Intent it=new Intent(Intent.ACTION_SEND);
String[] tos={"me@abc.com"};
String[] ccs={"you@abc.com"};
it.putExtra(Intent.EXTRA_EMAIL, tos);
it.putExtra(Intent.EXTRA_CC, ccs);
it.putExtra(Intent.EXTRA_TEXT, "The email body text");
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
it.setType("message/rfc822");
startActivity(Intent.createChooser(it, "Choose Email Client"));
//傳送附件
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/mysong.mp3");
sendIntent.setType("audio/mp3");
startActivity(Intent.createChooser(it, "Choose Email Client"));
~~~
###播放多媒體
~~~
Uri uri = Uri.parse("file:///sdcard/song.mp3");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
it.setType("audio/mp3");
startActivity(it);
Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
~~~
###Market 相關
~~~
//尋找某個應用
Uri uri = Uri.parse("market://search?q=pname:pkg_name");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
//where pkg_name is the full package path for an application
//顯示某個應用的相關信息
Uri uri = Uri.parse("market://details?id=app_id");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
//where app_id is the application ID, find the ID
//by clicking on your application on Market home
//page, and notice the ID from the address bar
~~~
###Uninstall 應用程序
~~~
Uri uri = Uri.fromParts("package", strPackageName, null);
Intent it = new Intent(Intent.ACTION_DELETE, uri);
startActivity(it);
~~~
參考:
[http://www.cnblogs.com/smyhvae/p/3959204.html](http://www.cnblogs.com/smyhvae/p/3959204.html "http://www.cnblogs.com/smyhvae/p/3959204.html")
[http://blog.csdn.net/yulei_qq/article/details/21233901](http://blog.csdn.net/yulei_qq/article/details/21233901 "http://blog.csdn.net/yulei_qq/article/details/21233901")
[http://zy77612.iteye.com/blog/764699](http://zy77612.iteye.com/blog/764699 "http://zy77612.iteye.com/blog/764699")
- 前言
- Appcompat_V7問題
- This Android SDK requires Android Developer Toolkit version 23.0.0 or above
- 創建Android項目不自動生成Activity,layout目錄為空
- 新建android項目gen目錄下未生成R文件
- 手機安全衛士02:splash界面ui
- 知識點:Android控件系列之Toast
- 手機安全衛士03:獲取更新的服務器配置,顯示更新對話框
- 異常處理:android.os.NetworkOnMainThreadException--多線程問題
- 知識點:Android控件系列之對話框AlertDialog.Builder
- 手機安全衛士04_01:界面(Activity)之間的切換,Activity和任務棧
- 知識點:Android控件系列之ProgressDialog與ProgressBar
- 手機安全衛士04_02:從服務器下載并安裝新版本安裝包
- 知識點:Intent
- 知識點:Adapter適配器
- 手機安全衛士05_1:程序主界面
- 手機安全衛士05_2:程序主界面,為每個條目添加事件
- 知識點:動態設置布局LayoutInflater
- 知識點:SharedPreferences
- 手機安全衛士06-手機防盜之自定義對話框
- 手機安全衛士07-手機防盜之進入限制
- 手機安全衛士08-一些布局和顯示的細節:State List
- 手機安全衛士09-手機防盜界面設置向導1
- 手機安全衛士10-設置向導之綁定SIM卡