Android:BroadcastReceiver

Broadcast分類
java

註冊方式:android

  • 動態廣播安全

    • 在代碼中註冊receiverapp

    • 必定要手動在onDestroy()時調用unregisterReveiver()來取消註冊ide

  • 靜態廣播this

    • 在AndroidManifest.xml中註冊receiver(主要是設定action)spa

動態廣播:.net

1. 在代碼中設置receiver、監聽的廣播類型並進行註冊:code

 public class MainActivity extends Activity {
    private NetworkChangeReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");

        receiver = new NetworkChangeReceiver();
        registerReceiver(receiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);//remember to unregister manually
        super.onDestroy();
    }
}

2. 定義receiver的行爲:繼承BroadcastReceiver並在覆寫onReceiver()時定義好接收到廣播時處理的邏輯:
orm

 public class NetworkChangeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if(networkInfo != null && networkInfo.isAvailable())
            Toast.makeText(context, "Network is available.", Toast.LENGTH_SHORT).show();
        else
            Toast.makeText(context, "Network is unavailable.", Toast.LENGTH_SHORT).show();
    }
}

3. 在AndroidManifest.xml中定義必要的權限,主要<uses-permission>標籤位於<manifest>的下一級,即與<application>同級:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

 

靜態廣播(以開機啓動的廣播爲例)

1. 定義receiver的行爲:

public class BootCompleteReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Boot complete.", Toast.LENGTH_LONG).show();
    }
}

2. 在AndroidManifest.xml中定義receiver(與<activity>同級,<application>的子元素):

<receiver android:name=".MyBroadcast">
    <intent-filter android:priority="100">
        <action android:name="com.scv.lawrence.MY_BROADCAST"/>
    </intent-filter>
</receiver>

3. 在AndroidManifest.xml中添加相應權限(<application>同級,<manifest>的子元素):

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

 

接收順序:

  • 標準(Normal broadcast)

    • 默認的廣播方式,即broadcast發出後,全部receiver幾乎在同時接收到。

  • 有序(Ordered broadcast)

    • receiver根據設定的優先級(priority)來決定broadcast的傳遞順序,較高優先級的receiver能夠選擇攔截該broadcast阻止其向後傳播

  • 兩者區別

    • 發送廣播時,標準廣播調用的是sendBroadcast(),有序廣播調用的是sendOrderedBroadcast()

    • 接收廣播時(在AndroidManifest.xml中註冊receiver),標準廣播不用在<intent-filter>中設置android:priority屬性,有序廣播則須要設定一個整數,數值越大priority越高

在代碼中發送自定義的標準/無序廣播:

Button sendBroadcast = (Button) findViewById(R.id.broadcast);
sendBroadcast.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent("com.scv.lawrence.MY_BROADCAST");
        sendBroadcast(intent);
//      sendOrderedBroadcast(intent, null);
    }
});

 在AndroidManifest.xml中定義(父元素爲<application>,即與<activity>同級):

<receiver android:name=".MyBroadcast">
    <intent-filter android:priority="100">
        <action android:name="com.scv.lawrence.MY_BROADCAST"/>
    </intent-filter>
</receiver>

  

廣播範圍:

  • 全局廣播

    • 非LocalBroadcastManager進行發送或接收的廣播即爲全局廣播

  • 本地廣播

    • 發送/接收的broadcast只限於當前app範圍內,安全性比全局高

    • 與全局廣播的區別在於本地廣播依靠LocalBroadcastManager進行註冊、發送及註銷receiver

 本地廣播:

1. 定義接收到廣播的行爲:

public class LocalBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Get the local broadcast.", Toast.LENGTH_SHORT).show();
    }
}

 

2. 和動態廣播差很少,區別主要在使用LocalBroadcastManager的實例來進行操做:

public class MainActivity extends Activity {
    private LocalBroadcastManager localBroadcastManager;
    private LocalBroadcastReceiver localReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Local Broadcast
        localBroadcastManager = LocalBroadcastManager.getInstance(MainActivity.this);

        final Button localBroadcast = (Button) findViewById(R.id.local_broadcast);
        localBroadcast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.scv.lawrence.LOCAL_BROADCAST");
                localBroadcastManager.sendBroadcast(intent);
            }
        });

        IntentFilter localIntentFilter = new IntentFilter();
        localIntentFilter.addAction("com.scv.lawrence.LOCAL_BROADCAST");

        localReceiver = new LocalBroadcastReceiver();
        localBroadcastManager.registerReceiver(localReceiver, localIntentFilter);
    }

    @Override
    protected void onDestroy() {
        localBroadcastManager.unregisterReceiver(localReceiver);
        super.onDestroy();
    }
}

 

3. 在AndroidManifest.xml中配置permission. (若有必要)


參考: 《第一行代碼:Android》 郭霖(著) 

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息