一、网络状态接收者是一个广播接收者当网络状态发生改变时会收到网络状态改变的广播
本例当网络状态改变时会进行相应处理 例如当断网时会发出通知点击通知后 会打开网络设置界面
代码如下:
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 }