廣播接收者BroadcastReceiver

廣播接收者簡介:

  1. 廣播接收者,Android 四大組件之一,用來接收Android 系統 或者是應用程序發送出來的各種廣播信息的。
  2. 廣播:系統/應用程序 發生狀態改變的時候,需要想系統中通知其他的應用程序,進行一些操作,這個信息就是廣播。
  3. 廣播接收者:應用程序中,用於接收系統或者應用程序發送的消息的組件,當廣播收到的時候,會自動的啓動。
  4. 廣播的分類:有序、無序

用法:

    <!-- 清單文件註冊,註冊廣播接受者,靜態註冊 -->
        <receiver android:name=".NetworkReceiver">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
            </intent-filter>
        </receiver>

/**
 * 廣播接受者,內部只有一個onReceive的方法,用來接收數據
 */
public class NetworkReceiver extends BroadcastReceiver {
    private static final String TAG = "NetworkReceiver";
    /**
     * 當廣播信息收到的時候,回掉這個方法,intent內部包含了廣播的完整信息
     * @param context
     * @param intent
     */
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "onReceive1111111111: "+intent);
        //廣播接收者使用模式

        //因爲他可以支持多個種類action的接受
        String action = intent.getAction();
        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
            ConnectivityManager manager=
                    (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = manager.getActiveNetworkInfo();  //返回正在連接的網絡信息,null代表飛行模式
            if (networkInfo != null) {
                int type = networkInfo.getType();
                switch (type){
                    case ConnectivityManager.TYPE_WIFI:
                        Log.d(TAG, "onReceive: 111111111 wifi");
                        break;
                    case ConnectivityManager.TYPE_MOBILE:
                        Log.d(TAG, "onReceive: 11111111流量");
                        break;
                }
                //有網絡
            }else {
                Log.d(TAG, "onReceive: 1111111111無網絡連接");
                //無網絡
            }
        }
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章