//Activity注册NetMonitor netMonitor = new NetMonitor();netMonitor.start(this.getApplicationContext());netMonitor.addListener(this);
//网络监听的回调
@OverrIDe public voID onNetworkChange() { Log.e("TAG", "回调"); }
//注册动态广播实时监听
public class NetMonitor { private List<OnNetworkchangelistener> onNetworkchangelisteners; private NetbroadcastReceiver netbroadcastReceiver; private Context context; private ExecutorService executor = Executors.newCachedThreadPool(); private Runnable netChangeRunnable = new Runnable() { @OverrIDe public voID run() { notifyNetworkChange(); } }; public NetMonitor() { onNetworkchangelisteners = new ArrayList<>(); } /** * 开启网络监听 */ public voID start(Context context) { Context applicationContext = context.getApplicationContext(); this.context = applicationContext; netbroadcastReceiver = new NetbroadcastReceiver(); IntentFilter filter = new IntentFilter(); //设置action为CONNECTIVITY_ACTION filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); //动态注册广播 applicationContext.registerReceiver(netbroadcastReceiver, filter); } /** * 停止网络监听 */ public voID stop() { if (context == null) { return; } if (netbroadcastReceiver != null) { context.unregisterReceiver(netbroadcastReceiver); } context = null; } /** * 注册监听 */ public voID addListener(OnNetworkchangelistener Listener) { if (Listener != null) { onNetworkchangelisteners.add(Listener); } } /** * 注销监听 */ public voID removeListener(OnNetworkchangelistener Listener) { if (Listener != null) { onNetworkchangelisteners.remove(Listener); } } /** * 通知网络状态更新 */ private voID notifyNetworkChange() { for (OnNetworkchangelistener Listener : onNetworkchangelisteners) { if (Listener != null) { Listener.onNetworkChange(); } } } private class NetbroadcastReceiver extends broadcastReceiver { @OverrIDe public voID onReceive(Context context, Intent intent) { String action = intent.getAction(); //如果action是网络变化,则执行以下处理逻辑 if (action != null && action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { //网络状态可以根据自己项目工具类获取 int type = NetworkUtils.getNetWorkType(TextApp.getInstance()); if (type == NetworkUtils.NETWORK_NO) { Log.e("TAG", "断开"); executor.execute(netChangeRunnable); } else if (type != NetworkUtils.NETWORK_WIFI) { executor.execute(netChangeRunnable); Log.e("TAG", "连上移动网络了"); }else { Log.e("TAG", "连上(wifi)"); } } } }}
//接口
public interface OnNetworkchangelistener { voID onNetworkChange();}
总结
以上是内存溢出为你收集整理的Android 监测网络切换全部内容,希望文章能够帮你解决Android 监测网络切换所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)