网络状态监听
网络状态监听
定义一个广播接收器和状态变化接口
public class NetBroadcastReceiver extends BroadcastReceiver {
public static ArrayList<NetEventHandler> mListeners = new ArrayList<NetEventHandler>();
private static String NET_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
@Override
public void onReceive(Context context, Intent intent) {
Log.i("dsc", "dsc");
if (intent.getAction().equals(NET_CHANGE_ACTION)) {
MainActivity.mNetWorkState = NetUtil.getNetworkState(context);
if (mListeners.size() > 0)//通知接口完成加载
for (NetEventHandler handler : mListeners) {
handler.onNetChange();
}
}
}
public interface NetEventHandler {
public void onNetChange();
}
}
网络状态工具类
public class NetUtil {
public static final int NETWORN_NONE = 0;
public static final int NETWORN_WIFI = 1;
public static final int NETWORN_MOBILE = 2;
public static int getNetworkState(Context context) {
ConnectivityManager connManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
// Wifi
State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.getState();
if (state == State.CONNECTED || state == State.CONNECTING) {
return NETWORN_WIFI;
}
// 3G
state = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
.getState();
if (state == State.CONNECTED || state == State.CONNECTING) {
return NETWORN_MOBILE;
}
return NETWORN_NONE;
}
}
主要实现
public class MainActivity extends AppCompatActivity implements NetBroadcastReceiver.NetEventHandler{
public static int mNetWorkState;
private NetBroadcastReceiver netReceiver;//网络状态监测
private boolean netState = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//注册网络监听广播
regist();
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e("myLog", "TaskListFragment执行销毁");
unregisterReceiver(netReceiver);
}
/**
* 注册广播
*/
private void regist() {
netReceiver = new NetBroadcastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(netReceiver, filter);
NetBroadcastReceiver.mListeners.add(this);
}
@Override
public void onNetChange() {
if (getApplicationContext()== null) {
return;
}
if (NetUtil.getNetworkState(this) == NetUtil.NETWORN_NONE) {//没有网络
netState = false;
Toast.makeText(this, "你的网络已断开连接,请检查网络!", Toast.LENGTH_SHORT).show();
} else if (NetUtil.getNetworkState(this) == NetUtil.NETWORN_WIFI) {//wifi网络
netState = true;
Toast.makeText(this, "你目前是wifi网络!", Toast.LENGTH_SHORT).show();
} else {//手机网络
netState = true;
Toast.makeText(this, "你目前是手机网络!", Toast.LENGTH_SHORT).show();
}
}
}
AndroidManifest注册
<receiver android:name=".NetBroadcastReceiver"/>