本文主要是介绍安卓广播动态监听网络工具类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
为满足日常开发需求,特此奉上,同时记录一下
1 创建 NetBroadcastReceiver类
public class NetBroadcastReceiver extends BroadcastReceiver {public NetChangeListener listener= MainActivity.listener;@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stub// 如果相等的话就说明网络状态发生了变化Log.e("------------", "onReceive: " );if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {int netWorkState = getNetWorkState(context);// 当网络发生变化,判断当前网络状态,并通过NetEvent回调当前网络状态if (listener != null) {listener.onChangeListener(netWorkState);}}}// 自定义接口public interface NetChangeListener {void onChangeListener(int status);}/*** 没有网络*/private static final int NETWORK_NONE = -1;/*** 移动网络*/private static final int NETWORK_MOBILE = 0;/*** 无线网络*/private static final int NETWORK_WIFI = 1;public static int getNetWorkState(Context context) {//得到连接管理器对象ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();//如果网络连接,判断该网络类型if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_WIFI)) {return NETWORK_WIFI;//wifi} else if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_MOBILE)) {return NETWORK_MOBILE;//mobile}} else {//网络异常return NETWORK_NONE;}return NETWORK_NONE;}
}
2 在Activity中使用便可
public class MainActivity extends Activity implements NetBroadcastReceiver.NetChangeListener{public static NetBroadcastReceiver.NetChangeListener listener;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);listener=this;if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//实例化IntentFilter对象IntentFilter filter = new IntentFilter();filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");NetBroadcastReceiver netBroadcastReceiver = new NetBroadcastReceiver();//注册广播接收registerReceiver(netBroadcastReceiver, filter);}}@Overridepublic void onChangeListener(int status) {if (status==0) {Toast.makeText(this, "移动网络", Toast.LENGTH_SHORT).show();} else if (status==1) {Toast.makeText(this, "无线网络", Toast.LENGTH_SHORT).show();} else if (status==-1) {Toast.makeText(this, "没有网络", Toast.LENGTH_SHORT).show();}}
}
直接C V便好 ,有需求可以关注公众号,那里我会及时回答,这边可能会无法及时回复
这篇关于安卓广播动态监听网络工具类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!