廣播機制

安卓的廣播機制:

說明:廣播廣播,其實就是一個地方將信息傳播出去,只要有廣播接收器的地方都能同時接收到信息。安卓的廣播機制一般可以針對應用內的廣播,也可以針對跨應用廣播。例如電池的事件,電池快沒電的時候,會發送一個廣播,如果你的應用中有接收這個廣播,則就會調用廣播接收的程序。

廣播和Service都是在UI線程中處理的,所以使用廣播的時候,不能處理延遲很長的操作,否則會阻礙UI線程的更新。通過廣播,可以監聽外部APP發送過來的廣播消息,通過這些廣播消息,可以做出相應的處理。

看一個圖:


一些觀點:

  1. 在Android 中如果要發送一個廣播必須使用sendBroadCast 向系統發送對其感興趣的廣播接收器中
  2. 使用廣播必須要有一個intent 對象必設置其action動作對象
  3. 使用廣播必須在配置文件中顯式的指明該廣播對象
  4. 每次接收廣播都會重新生成一個接收廣播的對象
  5. 在BroadCast 中儘量不要處理太多邏輯問題,建議複雜的邏輯交給Activity 或者 Service 去處理


廣播例子,常駐型廣播

常駐型廣播,當你的應用程序關閉了,如果有廣播信息來,你寫的廣播接收器同樣的能接受到,他的註冊方式就是在你的應用程序中的AndroidManifast.xml進行註冊。

首先需要配置AndroidMainfest.xml

[html] view plain copy
 print?
  1. <!--  
  2.      android:name就是限定了只能在 TestReceiver   
  3.     廣播接收器中接收 android.intent.action.EDIT類型的廣播  
  4. -->  
  5. <receiver android:name=".TestReceiver" >  
  6.     <intent-filter>  
  7.         <action android:name="android.intent.action.EDIT" />  
  8.     </intent-filter>  
  9. </receiver>  
  10. <receiver android:name=".Test2Receiver" >  
  11.     <intent-filter>  
  12.         <action android:name="android.intent.action.EDIT" />  
  13.     </intent-filter>  
  14. </receiver>  


發送一個廣播 MainActivity.java:

[java] view plain copy
 print?
  1. package com.example.test.com;  
  2.   
  3.   
  4. import android.annotation.SuppressLint;  
  5. import android.app.Activity;  
  6. import android.content.Intent;  
  7. import android.os.Bundle;  
  8. import android.view.View;  
  9. import android.view.View.OnClickListener;  
  10. import android.view.Window;  
  11. import android.widget.Button;  
  12.   
  13. @SuppressLint("HandlerLeak")  
  14. public class MainActivity extends Activity {  
  15.   
  16.     private Button btn;  
  17.   
  18.     @Override  
  19.     protected void onCreate(Bundle savedInstanceState) {  
  20.         super.onCreate(savedInstanceState);  
  21.         requestWindowFeature(Window.FEATURE_NO_TITLE);  
  22.         setContentView(R.layout.activity_main);  
  23.   
  24.         btn = (Button) findViewById(R.id.button1);  
  25.         //圖片點擊的時候  
  26.         btn.setOnClickListener(new OnClickListener() {  
  27.   
  28.             @Override  
  29.             public void onClick(View v) {  
  30.                 Intent intent = new Intent();//採用intent發送數據  
  31.                 intent.setAction(Intent.ACTION_EDIT);//只發送給action爲ACTION_EDIT的對象  
  32.                 Bundle bundle = new Bundle();  
  33.                 bundle.putString("val""Hello World");  
  34.                 intent.putExtras(bundle);  
  35.                 //通過廣播方式發送該intent,只有特定action的接收者才能收到該廣播信息  
  36.                 MainActivity.this.sendBroadcast(intent);  
  37.             }  
  38.         });  
  39.     }  
  40.   
  41. }  

接收廣播,需要繼承BroadcastReceiver類,並且實現onReceive方法:

TestReceiver:

[java] view plain copy
 print?
  1. package com.example.test.com;  
  2.   
  3.   
  4. import android.content.BroadcastReceiver;  
  5. import android.content.Context;  
  6. import android.content.Intent;  
  7. import android.os.Bundle;  
  8.   
  9. public class TestReceiver extends BroadcastReceiver {  
  10.   
  11.     public TestReceiver() {  
  12.         System.out.println("TestReceiver");  
  13.   
  14.     }  
  15.   
  16.     @Override  
  17.     public void onReceive(Context context, Intent intent) {  
  18.         String action = intent.getAction();  
  19.         //這邊可以獲取Action的名稱  
  20.         if (action.equals(Intent.ACTION_EDIT)) {  
  21.             Bundle bundle = intent.getExtras();  
  22.             System.out.println("OnReceiver" + bundle.getString("val"));  
  23.         }  
  24.     }  
  25. }  


Test2Receiver:

[java] view plain copy
 print?
  1. package com.example.test.com;  
  2.   
  3.   
  4. import android.content.BroadcastReceiver;  
  5. import android.content.Context;  
  6. import android.content.Intent;  
  7. import android.os.Bundle;  
  8.   
  9. public class Test2Receiver extends BroadcastReceiver {  
  10.   
  11.     public Test2Receiver() {  
  12.         System.out.println("Test2Receiver");  
  13.   
  14.     }  
  15.   
  16.     @Override  
  17.     public void onReceive(Context context, Intent intent) {  
  18.         String action = intent.getAction();  
  19.         if (action.equals(Intent.ACTION_EDIT)) {  
  20.             Bundle bundle = intent.getExtras();  
  21.             System.out.println("OnReceiver2" + bundle.getString("val"));  
  22.         }  
  23.     }  
  24. }  

點擊按鈕後,控制檯效果:


接收器的生命週期:



廣播例子,非常駐型廣播

當應用程序結束了,廣播自然就沒有了,比如你在activity中的onCreate或者onResume中註冊廣播接收器在onDestory中卸載廣播接收器。這樣你的廣播接收器就一個非常駐型的了。這種也叫動態註冊。

[java] view plain copy
 print?
  1. package com.example.test.com;  
  2.   
  3.   
  4. import android.annotation.SuppressLint;  
  5. import android.app.Activity;  
  6. import android.content.Intent;  
  7. import android.content.IntentFilter;  
  8. import android.os.Bundle;  
  9. import android.view.View;  
  10. import android.view.View.OnClickListener;  
  11. import android.view.Window;  
  12. import android.widget.Button;  
  13.   
  14. @SuppressLint("HandlerLeak")  
  15. public class MainActivity extends Activity {  
  16.   
  17.     private Button       btn;  
  18.     private TestReceiver testReceiver;  
  19.   
  20.     @Override  
  21.     protected void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         requestWindowFeature(Window.FEATURE_NO_TITLE);  
  24.         setContentView(R.layout.activity_main);  
  25.   
  26.         //初始化的時候註冊  
  27.         IntentFilter filter = new IntentFilter();  
  28.         filter.addAction(Intent.ACTION_EDIT);  
  29.         testReceiver = new TestReceiver();  
  30.         registerReceiver(testReceiver, filter);  
  31.   
  32.         btn = (Button) findViewById(R.id.button1);   
  33.         btn.setOnClickListener(new OnClickListener() {  
  34.   
  35.             @Override  
  36.             public void onClick(View v) {  
  37.                 Intent intent = new Intent();//採用intent發送數據    
  38.                 intent.setAction(Intent.ACTION_EDIT);//只發送給action爲ACTION_EDIT的對象    
  39.                 Bundle bundle = new Bundle();    
  40.                 bundle.putString("val""Hello World");    
  41.                 intent.putExtras(bundle);    
  42.                 //通過廣播方式發送該intent,只有特定action的接收者才能收到該廣播信息    
  43.                 MainActivity.this.sendBroadcast(intent);    
  44.   
  45.             }  
  46.   
  47.         });  
  48.     }  
  49.   
  50.     @Override  
  51.     protected void onDestroy() {  
  52.         unregisterReceiver(testReceiver);  
  53.     }  
  54.   
  55. }  

[java] view plain copy
 print?
  1. package com.example.test.com;  
  2.   
  3.   
  4. import android.content.BroadcastReceiver;  
  5. import android.content.Context;  
  6. import android.content.Intent;  
  7. import android.os.Bundle;  
  8.   
  9. public class TestReceiver extends BroadcastReceiver {  
  10.   
  11.     public TestReceiver() {  
  12.         System.out.println("TestReceiver");  
  13.   
  14.     }  
  15.   
  16.     @Override  
  17.     public void onReceive(Context context, Intent intent) {  
  18.         String action = intent.getAction();  
  19.         //這邊可以獲取Action的名稱    
  20.         if (action.equals(Intent.ACTION_EDIT)) {  
  21.             Bundle bundle = intent.getExtras();  
  22.             System.out.println("OnReceiver" + bundle.getString("val"));  
  23.         }  
  24.     }  
  25. }  

下面是一個內部類實現廣播接收的例子,通過內部類實現,可以動態監聽廣播消息,並且對廣播進行UI界面上的處理

[java] view plain copy
 print?
  1. package com.example.test.com;  
  2.   
  3.   
  4. import android.app.Activity;  
  5. import android.content.BroadcastReceiver;  
  6. import android.content.Context;  
  7. import android.content.Intent;  
  8. import android.content.IntentFilter;  
  9. import android.os.Bundle;  
  10. import android.view.View;  
  11. import android.view.View.OnClickListener;  
  12. import android.view.Window;  
  13. import android.widget.Button;  
  14. import android.widget.Toast;  
  15.   
  16. public class MainActivity extends Activity {  
  17.   
  18.     private ButtonOnClickListener btnListener;  
  19.   
  20.     private Button btn;  
  21.   
  22.     @Override  
  23.     protected void onCreate(Bundle savedInstanceState) {  
  24.         super.onCreate(savedInstanceState);  
  25.         requestWindowFeature(Window.FEATURE_NO_TITLE);  
  26.         setContentView(R.layout.main);  
  27.         btn = (Button) findViewById(R.id.button1);  
  28.         btnListener = new ButtonOnClickListener();  
  29.         btn.setOnClickListener(btnListener);  
  30.   
  31.     }  
  32.   
  33.     class ButtonOnClickListener implements OnClickListener {  
  34.   
  35.         @Override  
  36.         public void onClick(View v) {  
  37.             Toast.makeText(getBaseContext(), "YES!", Toast.LENGTH_SHORT).show();  
  38.               
  39.             TestBroadcast testBroadCast = new TestBroadcast();  
  40.             IntentFilter filter = new IntentFilter();  
  41.             filter.addAction(Intent.ACTION_EDIT);    //只有持有相同的action的接受者才能接收此廣播  
  42.             registerReceiver(testBroadCast, filter); //註冊  
  43.               
  44.             Intent intent = new Intent();//採用intent發送數據      
  45.             Bundle bundle = new Bundle();  
  46.             bundle.putString("hello""world");  
  47.             intent.putExtras(bundle);  
  48.             intent.setAction(Intent.ACTION_EDIT);//只發送給action爲ACTION_EDIT的對象      
  49.             MainActivity.this.sendBroadcast(intent);    
  50.         }  
  51.     }  
  52.   
  53.     //通過內部類,可以實現UI修改  
  54.     class TestBroadcast extends BroadcastReceiver {  
  55.   
  56.         @Override  
  57.         public void onReceive(Context context, Intent intent) {  
  58.             Toast.makeText(context, "YES2!", Toast.LENGTH_SHORT).show();  
  59.             String action = intent.getAction();  
  60.             if (action.equals(Intent.ACTION_EDIT)) {  
  61.                 Bundle bundle = intent.getExtras();  
  62.                 btn.setText(bundle.getString("hello")); //更改btn的文字  
  63.             }  
  64.         }  
  65.     }  
  66.   
  67.   
  68.   
  69. }  


安卓系統廣播

[java] view plain copy
 print?
  1. String ADD_SHORTCUT_ACTION 動作:在系統中添加一個快捷方式。  
  2. String ALL_APPS_ACTION 動作:列舉所有可用的應用。輸入:無。  
  3. String ALTERNATIVE_CATEGORY 類別:說明 activity 是用戶正在瀏覽的數據的一個可選操作。  
  4. String ANSWER_ACTION 動作:處理撥入的電話。  
  5. String BATTERY_CHANGED_ACTION 廣播:充電狀態,或者電池的電量發生變化。  
  6. String BOOT_COMPLETED_ACTION 廣播:在系統啓動後,這個動作被廣播一次(只有一次)。  
  7. String BROWSABLE_CATEGORY 類別:能夠被瀏覽器安全使用的 activities 必須支持這個類別。  
  8. String BUG_REPORT_ACTION 動作:顯示 activity 報告錯誤。  
  9. String CALL_ACTION 動作:撥打電話,被呼叫的聯繫人在數據中指定。  
  10. String CALL_FORWARDING_STATE_CHANGED_ACTION 廣播:語音電話的呼叫轉移狀態已經改變。  
  11. String CLEAR_CREDENTIALS_ACTION 動作:清除登陸憑證 (credential)。  
  12. String CONFIGURATION_CHANGED_ACTION 廣播:設備的配置信息已經改變,參見 Resources.Configuration.  
  13. Creator CREATOR 無 無  
  14. String DATA_ACTIVITY_STATE_CHANGED_ACTION 廣播:電話的數據活動(data activity)狀態(即收發數據的狀態)已經改變。  
  15. String DATA_CONNECTION_STATE_CHANGED_ACTION 廣播:電話的數據連接狀態已經改變。  
  16. String DATE_CHANGED_ACTION 廣播:日期被改變。  
  17. String DEFAULT_ACTION 動作:和 VIEW_ACTION 相同,是在數據上執行的標準動作。  
  18. String DEFAULT_CATEGORY 類別:如果 activity 是對數據執行確省動作(點擊, center press)的一個選項,需要設置這個類別。  
  19. String DELETE_ACTION 動作:從容器中刪除給定的數據。  
  20. String DEVELOPMENT_PREFERENCE_CATEGORY 類別:說明 activity 是一個設置面板 (development preference panel).  
  21. String DIAL_ACTION 動作:撥打數據中指定的電話號碼。  
  22. String EDIT_ACTION 動作:爲制定的數據顯示可編輯界面。  
  23. String EMBED_CATEGORY 類別:能夠在上級(父)activity 中運行。  
  24. String EMERGENCY_DIAL_ACTION 動作:撥打緊急電話號碼。  
  25. int FORWARD_RESULT_LAUNCH 啓動標記:如果這個標記被設置,而且被一個已經存在的 activity 用來啓動新的 activity,已有 activity 的回覆目標 (reply target) 會被轉移給新的 activity。  
  26. String FOTA_CANCEL_ACTION 廣播:取消所有被掛起的 (pending) 更新下載。  
  27. String FOTA_INSTALL_ACTION 廣播:更新已經被確認,馬上就要開始安裝。  
  28. String FOTA_READY_ACTION 廣播:更新已經被下載,可以開始安裝。  
  29. String FOTA_RESTART_ACTION 廣播:恢復已經停止的更新下載。  
  30. String FOTA_UPDATE_ACTION 廣播:通過 OTA 下載並安裝操作系統更新。  
  31. String FRAMEWORK_INSTRUMENTATION_TEST_CATEGORY 類別:To be used as code under test for framework instrumentation tests.  
  32. String GADGET_CATEGORY 類別:這個 activity 可以被嵌入宿主 activity (activity that is hosting gadgets)。  
  33. String GET_CONTENT_ACTION 動作:讓用戶選擇數據並返回。  
  34. String HOME_CATEGORY 類別:主屏幕 (activity),設備啓動後顯示的第一個 activity。  
  35. String INSERT_ACTION 動作:在容器中插入一個空項 (item)。  
  36. String INTENT_EXTRA 附加數據:和 PICK_ACTIVITY_ACTION 一起使用時,說明用戶選擇的用來顯示的 activity;和 ADD_SHORTCUT_ACTION 一起使用的時候,描述要添加的快捷方式。  
  37. String LABEL_EXTRA 附加數據:大寫字母開頭的字符標籤,和 ADD_SHORTCUT_ACTION 一起使用。  
  38. String LAUNCHER_CATEGORY 類別:Activity 應該被顯示在頂級的 launcher 中。  
  39. String LOGIN_ACTION 動作:獲取登錄憑證。  
  40. String MAIN_ACTION 動作:作爲主入口點啓動,不需要數據。  
  41. String MEDIABUTTON_ACTION 廣播:用戶按下了“Media Button”。  
  42. String MEDIA_BAD_REMOVAL_ACTION 廣播:擴展介質(擴展卡)已經從 SD 卡插槽拔出,但是掛載點 (mount point) 還沒解除 (unmount)。  
  43. String MEDIA_EJECT_ACTION 廣播:用戶想要移除擴展介質(拔掉擴展卡)。  
  44. String MEDIA_MOUNTED_ACTION 廣播:擴展介質被插入,而且已經被掛載。  
  45. String MEDIA_REMOVED_ACTION 廣播:擴展介質被移除。  
  46. String MEDIA_SCANNER_FINISHED_ACTION 廣播:已經掃描完介質的一個目錄。  
  47. String MEDIA_SCANNER_STARTED_ACTION 廣播:開始掃描介質的一個目錄。  
  48. String MEDIA_SHARED_ACTION 廣播:擴展介質的掛載被解除 (unmount),因爲它已經作爲 USB 大容量存儲被共享。  
  49. String MEDIA_UNMOUNTED_ACTION 廣播:擴展介質存在,但是還沒有被掛載 (mount)。  
  50. String MESSAGE_WAITING_STATE_CHANGED_ACTION 廣播:電話的消息等待(語音郵件)狀態已經改變。  
  51. int MULTIPLE_TASK_LAUNCH 啓動標記:和 NEW_TASK_LAUNCH 聯合使用,禁止將已有的任務改變爲前景任務 (foreground)。  
  52. String NETWORK_TICKLE_RECEIVED_ACTION 廣播:設備收到了新的網絡 "tickle" 通知。  
  53. int NEW_TASK_LAUNCH 啓動標記:設置以後,activity 將成爲歷史堆棧中的第一個新任務(棧頂)。  
  54. int NO_HISTORY_LAUNCH 啓動標記:設置以後,新的 activity 不會被保存在歷史堆棧中。  
  55. String PACKAGE_ADDED_ACTION 廣播:設備上新安裝了一個應用程序包。  
  56. String PACKAGE_REMOVED_ACTION 廣播:設備上刪除了一個應用程序包。  
  57. String PHONE_STATE_CHANGED_ACTION 廣播:電話狀態已經改變。  
  58. String PICK_ACTION 動作:從數據中選擇一個項目 (item),將被選中的項目返回。  
  59. String PICK_ACTIVITY_ACTION 動作:選擇一個 activity,返回被選擇的 activity 的類(名)。  
  60. String PREFERENCE_CATEGORY 類別:activity是一個設置面板 (preference panel)。  
  61. String PROVIDER_CHANGED_ACTION 廣播:更新將要(真正)被安裝。  
  62. String PROVISIONING_CHECK_ACTION 廣播:要求 polling of provisioning service 下載最新的設置。  
  63. String RUN_ACTION 動作:運行數據(指定的應用),無論它(應用)是什麼。  
  64. String SAMPLE_CODE_CATEGORY 類別:To be used as an sample code example (not part of the normal user experience).  
  65. String SCREEN_OFF_ACTION 廣播:屏幕被關閉。  
  66. String SCREEN_ON_ACTION 廣播:屏幕已經被打開。  
  67. String SELECTED_ALTERNATIVE_CATEGORY 類別:對於被用戶選中的數據,activity 是它的一個可選操作。  
  68. String SENDTO_ACTION 動作:向 data 指定的接收者發送一個消息。  
  69. String SERVICE_STATE_CHANGED_ACTION 廣播:電話服務的狀態已經改變。  
  70. String SETTINGS_ACTION 動作:顯示系統設置。輸入:無。  
  71. String SIGNAL_STRENGTH_CHANGED_ACTION 廣播:電話的信號強度已經改變。  
  72. int SINGLE_TOP_LAUNCH 啓動標記:設置以後,如果 activity 已經啓動,而且位於歷史堆棧的頂端,將不再啓動(不重新啓動) activity。  
  73. String STATISTICS_REPORT_ACTION 廣播:要求 receivers 報告自己的統計信息。  
  74. String STATISTICS_STATE_CHANGED_ACTION 廣播:統計信息服務的狀態已經改變。  
  75. String SYNC_ACTION 動作:執行數據同步。  
  76. String TAB_CATEGORY 類別:這個 activity 應該在 TabActivity 中作爲一個 tab 使用。  
  77. String TEMPLATE_EXTRA 附加數據:新記錄的初始化模板。  
  78. String TEST_CATEGORY 類別:作爲測試目的使用,不是正常的用戶體驗的一部分。  
  79. String TIMEZONE_CHANGED_ACTION 廣播:時區已經改變。  
  80. String TIME_CHANGED_ACTION 廣播:時間已經改變(重新設置)。  
  81. String TIME_TICK_ACTION 廣播:當前時間已經變化(正常的時間流逝)。  
  82. String UMS_CONNECTED_ACTION 廣播:設備進入 USB 大容量存儲模式。  
  83. String UMS_DISCONNECTED_ACTION 廣播:設備從 USB 大容量存儲模式退出。  
  84. String UNIT_TEST_CATEGORY 類別:應該被用作單元測試(通過 test harness 運行)。  
  85. String VIEW_ACTION 動作:向用戶顯示數據。  
  86. String WALLPAPER_CATEGORY 類別:這個 activity 能過爲設備設置牆紙。  
  87. String WALLPAPER_CHANGED_ACTION 廣播:系統的牆紙已經改變。  
  88. String WALLPAPER_SETTINGS_ACTION 動作:顯示選擇牆紙的設置界面。輸入:無。  
  89. String WEB_SEARCH_ACTION 動作:執行 web 搜索。  
  90. String XMPP_CONNECTED_ACTION 廣播:XMPP 連接已經被建立。  
  91. String XMPP_DISCONNECTED_ACTION 廣播:XMPP 連接已經被斷開。  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章