本文主要是介绍利用广播接收者监听Android系统网络变化,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.自定义广播接收者
package com.onetoo.www.onetoo.receiver;import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;/*** Created by longShun on 2017/2/17.* desc 网络相关接收者*/
public class NetBroadCastReceiver extends BroadcastReceiver {private static final String TAG = "NetBroadCastReceiver";@Overridepublic void onReceive(Context context, Intent intent) {//如果是在开启wifi连接和有网络状态下if(ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())){ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo networkInfo = cm.getActiveNetworkInfo();if (networkInfo != null && networkInfo.isAvailable()) {Log.d(TAG, "onReceive:网络打开 ");//todo...相应处理}else {Log.d(TAG, "onReceive:网络关闭 ");}}}
}
2.代码中动态注册
private NetBroadCastReceiver netBroadCastReceiver;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);//注册网络监听netBroadCastReceiver = new NetBroadCastReceiver();IntentFilter intentFiler = new IntentFilter();//"android.net.conn.CONNECTIVITY_CHANGE"这个是网络变化时系统发出的广播 intentFiler.addAction("android.net.conn.CONNECTIVITY_CHANGE");registerReceiver(netBroadCastReceiver, intentFiler);}@Overrideprotected void onDestroy() {super.onDestroy();//解除注册unregisterReceiver(netBroadCastReceiver);}
这篇关于利用广播接收者监听Android系统网络变化的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!