判断当前是wifi 还是网络
Posted 马骝
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了判断当前是wifi 还是网络相关的知识,希望对你有一定的参考价值。
//判断当前是wifi 还是网络 public static boolean checkNetworkConnection(Context context) { final ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); final android.net.NetworkInfo wifi =connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); final android.net.NetworkInfo mobile =connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if(wifi.isAvailable()||mobile.isAvailable()) return true; else return false; }
public class extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { State wifiState = null; State mobileState = null; ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState(); mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState(); if (wifiState != null && mobileState != null && State.CONNECTED != wifiState && State.CONNECTED == mobileState) { // 手机网络连接成功 } else if (wifiState != null && mobileState != null && State.CONNECTED != wifiState && State.CONNECTED != mobileState) { // 手机没有任何的网络 } else if (wifiState != null && State.CONNECTED == wifiState) { // 无线网络连接成功 } } } //第一种 注册 <receiver android:name="com.test.NetworkBroadcast" android:label="NetworkConnection" > <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver> //第二种 可以在Activity的onCreate()方法中注册广播,在Activity的onDestory()方法中卸载广播。 private BroadcastReceiver networkBroadcast=new BroadcastReceiver(); private void registerNetworkReceiver() { IntentFilter filter = new //WifiManager.NETWORK_STATE_CHANGED_ACTION IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); this.registerReceiver(networkBroadcast, filter); } private void unRegisterNetworkReceiver() { this.unregisterReceiver(networkBroadcast); }
以上是关于判断当前是wifi 还是网络的主要内容,如果未能解决你的问题,请参考以下文章
如何判断“移动网络数据”是启用还是禁用(即使通过 WiFi 连接)?