一、网络状态接收者是一个广播接收者当网络状态发生改变时会收到网络状态改变的广播

本例当网络状态改变时会进行相应处理 例如当断网时会发出通知点击通知后 会打开网络设置界面

代码如下:

 package com.qf.broadcastreceiver06;

 import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;
import android.util.Log; /**
* 监测网络连接状态的广播接收器
* @author apple
*
*/
public class NetworkStateReceiver extends BroadcastReceiver { @Override
public void onReceive(Context context, Intent intent) {
// TODO 接收网络连接发生变化时的广播
Log.i("debug",intent.getAction()); //获取当前连接的网络消息(作业2: 封装读取网络连接状态的工具类) //1. 获取系统的网络连接管理组件
ConnectivityManager connMgr=
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); //2. 获取当前网络连接对象
NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo(); //3. 判断当前网络是否连接
if(activeNetworkInfo==null){
Log.i("debug", "当前网络未连接。。。");
//实现功能(作业1):发送通知,并点击通知打开网络设置页面
//Settings.ACTION_WIRELESS_SETTINGS 无线网络设置页面的意图
NotificationCompat.Builder builder = new NotificationCompat.Builder(context); builder.setContentTitle("网络未连接")
.setContentText("点击打开网络设置页面")
.setSmallIcon(R.drawable.ic_launcher)
.setDefaults(Notification.DEFAULT_ALL);
Intent intent1 = new Intent();
intent1.setAction(Settings.ACTION_WIRELESS_SETTINGS);
//可以当通知被点击时自动执行 startActiivty()
PendingIntent pending = PendingIntent.getActivity(context, 6, intent1, PendingIntent.FLAG_CANCEL_CURRENT); //跳转后通知会消失
builder.setContentIntent(pending); builder.setAutoCancel(true);//设置通知自动消失 Notification ntf = builder.build(); NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(88, ntf); }else{
Log.i("debug", "当前网络已连接。。。"); //4.获取连接的网络类型
int type = activeNetworkInfo.getType();
if(type==ConnectivityManager.TYPE_WIFI){
Log.i("debug", "当前网络类型:Wifi");
}else {
Log.i("debug", "当前网络类型:非Wifi");
}
}
} }

NetworkStateReceiver

NetworkStateReceiver的简单应用-LMLPHP

05-11 09:32