网络状态监听
定义一个广播接收器和状态变化接口
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"/>
时间: 2024-11-13 08:20:32