廣播接收者簡介:
- 廣播接收者,Android 四大組件之一,用來接收Android 系統 或者是應用程序發送出來的各種廣播信息的。
- 廣播:系統/應用程序 發生狀態改變的時候,需要想系統中通知其他的應用程序,進行一些操作,這個信息就是廣播。
- 廣播接收者:應用程序中,用於接收系統或者應用程序發送的消息的組件,當廣播收到的時候,會自動的啓動。
- 廣播的分類:有序、無序
用法:
<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);
String action = intent.getAction();
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
ConnectivityManager manager=
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
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無網絡連接");
}
}
}
}