首页 > 代码库 > 网络状态监听
网络状态监听
网络状态监听
定义一个广播接收器和状态变化接口
publicclassNetBroadcastReceiverextendsBroadcastReceiver{
publicstaticArrayList<NetEventHandler> mListeners =newArrayList<NetEventHandler>();
privatestaticString NET_CHANGE_ACTION ="android.net.conn.CONNECTIVITY_CHANGE";
@Override
publicvoid 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();
}
}
}
publicinterfaceNetEventHandler{
publicvoid onNetChange();
}
}
网络状态工具类
publicclassNetUtil{
publicstaticfinalint NETWORN_NONE =0;
publicstaticfinalint NETWORN_WIFI =1;
publicstaticfinalint NETWORN_MOBILE =2;
publicstaticint 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;
}
}
主要实现
publicclassMainActivityextendsAppCompatActivityimplementsNetBroadcastReceiver.NetEventHandler{
publicstaticint mNetWorkState;
privateNetBroadcastReceiver netReceiver;//网络状态监测
privateboolean netState =false;
@Override
protectedvoid onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//注册网络监听广播
regist();
}
@Override
publicvoid onDestroy(){
super.onDestroy();
Log.e("myLog","TaskListFragment执行销毁");
unregisterReceiver(netReceiver);
}
/**
* 注册广播
*/
privatevoid regist(){
netReceiver =newNetBroadcastReceiver();
IntentFilter filter =newIntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(netReceiver, filter);
NetBroadcastReceiver.mListeners.add(this);
}
@Override
publicvoid onNetChange(){
if(getApplicationContext()==null){
return;
}
if(NetUtil.getNetworkState(this)==NetUtil.NETWORN_NONE){//没有网络
netState =false;
Toast.makeText(this,"你的网络已断开连接,请检查网络!",Toast.LENGTH_SHORT).show();
}elseif(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注册
<receiverandroid:name=".NetBroadcastReceiver"/>
来自为知笔记(Wiz)
网络状态监听
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。