android获取及监听手机网络状态
目录
- 一、获取当前手机联网方式是WiFi还是手机4G数据
- 二、监听手机网络变化
- 总结
一、获取当前手机联网方式是WiFi还是手机4G数据
private boolean getNetworkType(){ ConnectivityManager mConnectivity = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); //检查网络链接 NetworkInfo info = mConnectivity.getActiveNetworkInfo(); int netType = mConnectivity.getActiveNetworkInfo().getType(); if (netType == ConnectivityManager.TYPE_WIFI) { //WIFI ChangYouLog.i(TAG,"当前是WIFI连接 isConnected = "+info.isConnected()); return info.isConnected(); } else if (netType == ConnectivityManager.TYPE_MOBILE) { //MOBILE ChangYouLog.i(TAG,"当前是手机网络连接 isConnected = "+info.isConnected()); return info.isConnected(); } else { ChangYouLog.i(TAG,"当前没有网络连接 isConnected = "+info.isConnected()); return false; } }
二、监听手机网络变化
private class MyBroadcastReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {//监听网络连接 //获取联网状态的NetworkInfo对象 NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); if (info != null) { //如果当前的网络连接成功并且网络连接可用 if (NetworkInfo.State.CONNECTED == info.getState() && info.isAvailable()) { if (info.getType() == ConnectivityManager.TYPE_WIFI){ ChangYouLog.i(TAG,"连接上WiFi"); }else if (info.getType() == ConnectivityManager.TYPE_MOBILE){ ChangYouLog.i(TAG,"连接上移动网络数据"); CYouLbyMicroClient.getInstance().gameEvent("Network_4G_reminder"); } } else { ChangYouLog.i(TAG,"网络断开"); } } } } }
注:需要添加网络状态权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
总结
到此这篇关于android获取及监听手机网络状态的文章就介绍到这了,更多相关android网络状态内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)