概述
开发中遇到一个问题,android监听网络时断开wifi或重新连接时会收到2个广播.在网上搜了下,大致说是系统底层服务的原因多广播了几次.
解决方法不难,用一个变量保存上次的网络状态就行了.下面直接上代码.
/**
*
* @author suhaishuang
*
*/
public class ListenNetStateService extends Service {
private ConnectivityManager connectivityManager;
private NetworkInfo info;
//前次开关状态
private boolean netBoolean = false;
//当前开关状态
private boolean netAvaliable =false;
//第一次加载
private boolean isFirst = true;
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
info = connectivityManager.getActiveNetworkInfo();
SharedPreferences sp = getSharedPreferences("config",Context.MODE_PRIVATE);
Editor edit = sp.edit();
Intent netIntent = new Intent();
netIntent.setAction("android.intent.action.netstate");
if(info != null){
netAvaliable = info.isAvailable();
}else{
netAvaliable = false;
}
if(isFirst){
netIntent.putExtra("netAble", netAvaliable);
sendBroadcast(netIntent);
edit.putBoolean("netAble", netAvaliable);
netBoolean = netAvaliable;
isFirst = false;
}else{
if(netBoolean != netAvaliable){
netIntent.putExtra("netAble", netAvaliable);
edit.putBoolean("netAble", netAvaliable);
sendBroadcast(netIntent);
netBoolean = netAvaliable;
}
}
edit.commit();
}
}
};
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
super.onCreate();
IntentFilter mFilter = new IntentFilter();
mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mReceiver, mFilter);
}
@Override
public void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
}
觉得文章有点用,对你有点帮助的,给赞一个或评论下呗
最后
以上就是顺利飞鸟为你收集整理的android网络监听状态改变收到2个广播处理的全部内容,希望文章能够帮你解决android网络监听状态改变收到2个广播处理所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复