廣播接收者(BroadcastReceiver)

廣播接收者(BroadcastReceiver)

1.定義廣播接受者

靜態注冊廣播

  • 定義類繼承BroadcastReceiver,重寫onReceive方法

    public class BroadCastReceiverDemo extends BroadcastReceiver {
    
      @Override
      public void onReceive(Context context, Intent intent) {
    
          Toast.makeText(context,"廣播接受者--Boot Complete.",Toast.LENGTH_LONG).show();
      }
    
    }
    
  • 清單文件中聲明<receiver>,需要在其中配置<intent-filter>指定接收廣播的動作

    <!-- 開機廣播接受者 -->
    <receiver android:name=".BroadCastReceiverDemo">
         <intent-filter>
              <!-- 注冊開機廣播地址-->
              <action android:name="android.intent.action.BOOT_COMPLETED"/>
              <category android:name="android.intent.category.DEFAULT" />
          </intent-filter>
     </receiver>
    
  • 當接收到匹配廣播之后就會執行onReceive方法

     @Override
      public void onReceive(Context context, Intent intent) {
    
          Toast.makeText(context,"廣播接受者----Boot Complete.",Toast.LENGTH_LONG).show();
      }
    
  • BroadcastReceiver的優先級

     <!-- 開機廣播接受者 -->
    <receiver android:name=".BroadCastReceiverDemo">
         <intent-filter android:priority="2147483647">
              <!-- 注冊開機廣播地址-->
              <action android:name="android.intent.action.BOOT_COMPLETED"/>
              <category android:name="android.intent.category.DEFAULT" />
          </intent-filter>
     </receiver>
    

    2147483647是最高優先級,默認是0.

動態注冊廣播

  • BroadcastReceiver除了在清單文件中聲明,也可以在代碼中聲明,使用registerReceiver方法注冊Receiver

    public class MainActivity extends Activity {
    
       private CodeReceiver receiver;
       private IntentFilter filter;
    
       @Override
       protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
           
            filter = new IntentFilter("android.intent.action.SCREEN_ON");
            filter.setPriority(100);             //優先級
            receiver = new CodeReceiver();
           
            registerReceiver(receiver, filter);  // Activity創建時注冊接收者
       }
      
       @Override
       protected void onDestroy() {
            super.onDestroy();
            unregisterReceiver(receiver);       // Activity退出時注銷接收者
       }
    
    }
    

2.發送廣播

無序廣播

  • 使用sendBroadcast方法發送
  • 被所有廣播接收者接收,無序,不可中斷
  • 廣播時可設置接收者權限,僅當接收者含有權限才能接收
  • 接收者的<receiver>也可設置發送方權限,只接收含有權限應用的廣播

無序廣播發送方法

void sendBroadcast (Intent intent, String receiverPermission)

參數:

intent The Intent to broadcast; 傳給接收者的意圖 all receivers matching this Intent will receive the broadcast.所有匹配的廣播接受者都回收到這一意圖

receiverPermission (optional)可選的 String naming a permission that a receiver must hold in order to receive your broadcast.一個接收者必須擁有的權限 If null, no permission is required. 如果為null,則沒有要求

示例:

sendBroadcast(intent, null);

有序廣播

  • 使用sendOrderedBroadcast方法發送
  • 接收者可以在<intent-filter>中定義android:priority定義優先級,數字越大優先級越高
  • 被各個廣播接收者逐個接收,中途可以中斷或者添加數據
abortBroadcast()  
getResultExtras(true).putString("data", "新增數據");
<receiver android:name="com.top.myreceiver.MyReceiver1" >
     <intent-filter android:priority="1000">
         <action android:name="com.top.mybroadcast.xxx" />
     </intent-filter>
</receiver>

<receiver android:name="com.top.myreceiver.MyReceiver2" >
    <intent-filter android:priority="500">
      <action android:name="com.top.mybroadcast.xxx"/>
    </intent-filter>
</receiver>
        
<receiver android:name="com.top.myreceiver.MyReceiver3" >
    <intent-filter android:priority="100">
         <action android:name="com.top.mybroadcast.xxx" />
    </intent-filter>
</receiver>

  • 有序廣播發送方法
void sendOrderedBroadcast (Intent intent, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)

參數
intent* The Intent to broadcast; 傳給接收者的意圖 all receivers matching this Intent will receive the broadcast.所有匹配的廣播接受者都回收到這一意圖

receiverPermission (optional)可選的 String naming a permission that a receiver must hold in order to receive your broadcast.一個接收者必須擁有的權限 If null, no permission is required. 如果為null,則沒有要求

resultReceiver Your own BroadcastReceiver to treat as the final receiver of the broadcast. 指定一的廣播的最終接受者(必須執行的)
scheduler A custom Handler with which to schedule the resultReceiver callback;指定你的接收者回掉的handler; if null it will be scheduled in the Context's main thread. 如果為空,則默認為主線程
initialCode An initial value for the result code.初始的結果碼 Often Activity.RESULT_OK. 通常設置

initialData An initial value for the result data.初始的結果數據 Often null. 通常為null

initialExtras An initial value for the result extras.初始化附加信息bundle; Often null通常為null

示例

Intent intent = new Intent("com.top.broadcast.TEST");         // 創建意圖對象, 設置廣播的動作
intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); // 廣播是否啟動那些沒有啟動過的應用
intent.putExtra("data", "最初的數據!!!");                                  // 這里的數據不會被修改
Bundle bundle = new Bundle();
bundle.putString("name", "張三");
sendOrderedBroadcast(intent, "com.top.permission.BROADCAST", new ResultReciever(), null, 1, "MainActivity", bundle);

短信黑名單

  • Android系統在收到短信的時候會發送一條有序廣播,我們如果定義一個接收者接收這個廣播,就可以得到短信內容,也可以攔截短信
  • 定義廣播接收者接收廣播android.provider.Telephony.SMS_RECEIVED
  • 在onReceive方法內部調用Intent的getExtras()再調用get()獲取其中pdus字段,得到一個Object[],其中每一個元素都是一個byte[]
  • 通過SmsMessage類的createFromPdu方法創建SmsMessage對象
  • 從SmsMessage對象中即可獲取發送者號碼、短信內容、發送時間等信息
  • 需要接收短信權限:<uses-permission android:name="android.permission.RECEIVE_SMS"/>
  • Android系統中收到短信的通知是一個有序通知,我們如需攔截垃圾短信,可以配置較高的priority,收到信息進行判斷是否abortBroadcast()

自動IP撥號

  • 定義廣播接收者接收 android.intent.action.NEW_OUTGOING_CALL
  • 需要權限 <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
  • 在onReceive方法中使用getResultData() 和 setResultData() 方法獲取和設置電話號碼

廣播接收者生命周期 Broadcast receiver lifecycle

  • 廣播接收者的生命周期是非常短暫的,在接收到廣播的時候創建,onReceive()方法結束之后銷毀。當廣播消息抵達接收器時,Android調用它的onReceive()方法并將包含消息的Intent對象傳遞給它。廣播接收器僅在它執行這個方法時處于活躍狀態。當onReceive()返回后,它即為失活狀態。
    擁有一個活躍狀態的廣播接收器的進程被保護起來而不會被殺死。但僅擁有失活狀態組件的進程則會在其它進程需要它所占有的內存的時候隨時被殺掉。
    //廣播接收器只有一個回調方法:void onReceive(Context curContext, Intent broadcastMsg)
  • 廣播接收者是在主線程中執線的,廣播接收者中不要做一些耗時的工作,否則會彈出Application No Response錯誤對話框
  • 最好也不要在廣播接收者中創建子線程做耗時的工作,因為廣播接收者被銷毀后進程就成為了空進程,很容易被系統殺掉
  • 耗時的較長的工作最好放在服務中完成

在android系統里面有很多內置的廣播事件

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容