Android連載23-跨程序廣播、有序廣播

1、跨程序發送廣播

  • 廣播是一種能夠跨進程的通訊方式;
  • 咱們來寫一個發送有序廣播的項目
  • 首先先創建一個BroadcastTest3項目
  • 而後寫一個接收廣播的類,繼承自BroadcastReceiver
package com.example.broadcasttest3;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class AnotherBroadcastReceiver extends BroadcastReceiver {
 @Override
 public void onReceive(Context context,Intent intend) {
  Toast.makeText(context, "receive in AnotherBroadcastReceiver",Toast.LENGTH_SHORT).show();
 }
}
  • 而後在AndroidManifest.xml文件中註冊該類
    <application
    ...................省略代碼...................
        <receiver android:name=".AnotherBroadcastReceiver">
            <intent-filter>
                <action android:name="com.example.broadcasttest.MY_BROADCAST" />
            </intent-filter>
        </receiver>
    </application>
  • 能夠看到該類接受的是com.example.broadcasttest.MY_BROADCAST的廣播
  • 接下來咱們安裝好這個項目2
  • 咱們回到項目1,點擊send broadcast按鈕,會出現
    23.1
  • 而後緊接着會出現另外一個項目的提示
    23.2
  • 這就證實了咱們應用程序發出的廣播是能夠被其餘程序所接收到的。

注意:com.example.broadcasttest.MY_BROADCAST的廣播已經在第一個項目的Androidmanifest.xml文件中定義好了。java

2、發送有序廣播

  • 咱們聚焦回項目1
  • 接下來咱們發送有序廣播,首先先修改觸發廣播的方法,在MainActivity.java
//將sendBroadcast(intent);修改成以下有序廣播的方法
sendOrderedBroadcast(intent,null);
  • 該方法首先傳入intent,第二個參數是與權限相關的字符串,這裏傳入null便可
  • 而後給咱們的項目1的AndroidManifest.xml中文件添加優先級,表明項目1,在項目2以前得到該廣播
        <receiver android:name=".MyBroadcastReceiver">
            <intent-filter android:priority="100">
                <action android:name="com.example.broadcasttest.MY_BROADCAST"/>
            </intent-filter>
        </receiver>
  • 其實添加了一個屬性而已android:priority="100"
  • 固然這個項目1,也能夠截斷這個廣播不讓它繼續傳播,修改接收類MyBroadcastReceiver
 public void onReceive(Context context,Intent intent) {
  Toast.makeText(context, "received in MyBroadcastReceiver", Toast.LENGTH_SHORT).show();
  abortBroadcast();
 }
  • 也就是多加了一個截斷方法而已

3、使用本地廣播

  • 咱們上面介紹的都是全局廣播,全部程序均可以接收,因此會有安全性問題,同時也容易造成垃圾廣播
  • android給咱們提供了只在本程序裏發送接收的廣播,使用LocalBroadcastManager來管理
  • 咱們下次連載再進行修改代碼。

4、源碼:

相關文章
相關標籤/搜索