標籤:
一、網路狀態接收者是一個廣播接收者當網路狀態發生改變時會收到網路狀態改變的廣播
本例當網路狀態改變時會進行相應處理 例如當斷網時會發出通知點擊通知後 會開啟網路設定介面
代碼如下:
1 package com.qf.broadcastreceiver06; 2 3 import android.app.Notification; 4 import android.app.NotificationManager; 5 import android.app.PendingIntent; 6 import android.content.BroadcastReceiver; 7 import android.content.Context; 8 import android.content.Intent; 9 import android.net.ConnectivityManager;10 import android.net.NetworkInfo;11 import android.provider.Settings;12 import android.support.v4.app.NotificationCompat;13 import android.util.Log;14 15 /**16 * 監測網路連接狀態的廣播接收器17 * @author apple18 *19 */20 public class NetworkStateReceiver extends BroadcastReceiver {21 22 @Override23 public void onReceive(Context context, Intent intent) {24 // TODO 接收網路連接發生變化時的廣播25 Log.i("debug",intent.getAction());26 27 //擷取當前串連的網路訊息(作業2: 封裝讀取網路連接狀態的工具類)28 29 //1. 擷取系統的網路連接管理組件30 ConnectivityManager connMgr=31 (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);32 33 //2. 擷取當前網路連接對象34 NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();35 36 //3. 判斷當前網路是否串連37 if(activeNetworkInfo==null){38 Log.i("debug", "當前網路未串連。。。");39 //實現功能(作業1):發送通知,並點擊通知開啟網路設定頁面40 //Settings.ACTION_WIRELESS_SETTINGS 無線網路設定頁面的意圖41 NotificationCompat.Builder builder = new NotificationCompat.Builder(context);42 43 builder.setContentTitle("網路未串連")44 .setContentText("點擊開啟網路設定頁面")45 .setSmallIcon(R.drawable.ic_launcher)46 .setDefaults(Notification.DEFAULT_ALL);47 Intent intent1 = new Intent();48 intent1.setAction(Settings.ACTION_WIRELESS_SETTINGS);49 //可以當通知被點擊時自動執行 startActiivty()50 PendingIntent pending = PendingIntent.getActivity(context, 6, intent1, PendingIntent.FLAG_CANCEL_CURRENT); //跳轉後通知會消失51 builder.setContentIntent(pending);52 53 builder.setAutoCancel(true);//設定通知自動消失54 55 Notification ntf = builder.build();56 57 NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);58 59 manager.notify(88, ntf);60 61 }else{62 Log.i("debug", "當前網路已串連。。。");63 64 //4.擷取串連的網路類型65 int type = activeNetworkInfo.getType();66 if(type==ConnectivityManager.TYPE_WIFI){67 Log.i("debug", "當前網路類型:Wifi");68 }else {69 Log.i("debug", "當前網路類型:非Wifi");70 }71 }72 }73 74 }NetworkStateReceiver
NetworkStateReceiver的簡單應用