android的intent使用方法
1. 說明
Android中提供了Intent機制來協助應用間或者應用程序內部的交互與通訊。
Intent的兩種基本用法:一種是顯式的Intent,即在構造Intent對象時就指定接收者,這種方式與普通的函數調用類似;另一種是隱式的Intent,即Intent的發送者在構造Intent對象時,並不知道接收者是誰,只是指出接收者的一些特性(比如說啟動音樂播放軟件)
2. 使用方法
1) 啟動服務
a) 關鍵函數
context.startService()或context.bindService()
b) 示例
Intent i = new Intent(this, MyTestService.class);
this.startService(i); // 啟動service
2) 發送廣播
a) 關鍵函數
context.sendBroadcast()
b) 發送方
String msg = “test”;
Intent i = new Intent(“com.test.bc”);
i.pubExtra(“msg”, msg);
this.sendBroadcase(i);
c) 接收方
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_MEDIA_EJECT);
registerReceiver(mReceiver.interFilter);
3) 啟動應用程序
a) 關鍵函數
context.startActivity()
b) 示例
Intent intent =
new Intent(“com.android.browser“, “com.android.browser.BrowserActivity“);
startActivity(intent);
3. Intent的組成
Intent的參數可多可少,系統根據不同的參數組合過濾出一個或多個適合規則的界面
1) 調用方:以下幾個規則可以同時指定,也可以指定一部分或幾部分
Component:指定包名類名來調用(見上例),它是晚綁定,不會在編譯時報錯
Action:指定做什么的規則(比如ACTION_DIAL指定撥號類型應用),以供過濾
Data:提供的重要數據,通常是Uri,同時也提供數據的類型,以供過濾
Type:用於指定類型,以供過濾(比如ACTION_VIEW同時指定為Type為Image,則調出瀏覽圖片的應用)
Category:指定范圍
Extras:通過Bundle類傳參, 數據多,數據量大時用它傳
Flags:標志位(比如FLAG_ACTIVITY_NEW_TASK指定新開一個任務)
2) 被調用方
在AndroidManifest.xml中的<intent-filter>中聲明規則
例如: 一般程序都需要在inter-filter中加入android.intent.category.LAUNCHER的聲明, 以便被程序啟動器(Launcher)識別, 即以點擊圖標的方式供用戶運行
3) 示例
Intent intent = new Intent();
intent.setClassName(“com.android.browser“,
“com.android.browser.BrowserActivity“); // 打開瀏覽器
Uri data = Uri.parse(“http://www.google.com“);
intent.setData(data); // 打開某網頁
intent.addFlag(Intent.FLAG_ACTIVITY_NEW_TASK); // 以新建任務方式打開
intent.setAction(Intent.ACTION_VIEW); // 以瀏覽方式打開
startActivity(intent);
4. Intent的源碼實現
1) Intent解析,過濾規則對應出具體應用
frameworks/base/core/java/android/content/IntentFilter.java
2) Intent定義,規定程序中的使用的Define與xml中字串的對應關系
frameworks/base/core/java/android/content/Intent.java