我们在Android应用开发中有时必须实时监听这个程序的实时网络状态,还好Android在网络断开与连接时都会发送系统广播,我们通过接收系统的广播就可以实现网络的实时监听。
1.定义一个名为MyBroadcastReceiver的广播接收器并且实现BroadcastReceiver,重载 onReceive()函数,并在里面对网络状态进行判断:
package com.broadcast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class MyBroadcastReceiver extends BroadcastReceiver {
private SharedPreferences shared = null;
private int flag = -1;
@Override
public void onReceive(Context context, Intent intent) {
// 获得网络连接服务
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
// 判断是否正在使用GPRS网络
NetworkInfo mobileNetInfo = connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
// 判断是否正在使用WIFI网络
NetworkInfo wifiNetInfo = connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (!mobileNetInfo.isConnected() && !wifiNetInfo.isConnected()) {
flag = 0;
} else {
flag = 1;
}
System.out.println("--当前网络状态--flag--:" + flag);
shared = context.getSharedPreferences("UserInfo", 0);
Editor editor = shared.edit();
editor.putInt("network", flag);
editor.commit();
}
}
2.在合适的地方注册MyBroadcastReceiver,在onCreate()中调用如下函数进行广播的注册(动态注册):
/**
* 注册广播
*/
private void registerReceiver() {
// 注册广播接收器
IntentFilter filter = new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION);
MyBroadcastReceiver receiver = new MyBroadcastReceiver();
registerReceiver(receiver, filter);
}
3.记得加权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.INTERNET" />