检查手机是否使用WIFI或数据/ 3G

假设设备上启用了WIFI和Data / 3G,如何通过WiFi或数据计划检查用户是否正在使用互联网,假定它们都启用。 所以我不需要检查是否启用或禁用,我想要检测哪个用户实际使用。

我一直在做下面这个唯一的解决scheme吗?

WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if (WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState()) == NetworkInfo.DetailedState.CONNECTED) { String ssid = wifiInfo.getSSID(); } 

 void chkStatus() { final ConnectivityManager connMgr = (ConnectivityManager) this.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.isConnectedOrConnecting ()) { Toast.makeText(this, "Wifi", Toast.LENGTH_LONG).show(); } else if (mobile.isConnectedOrConnecting ()) { Toast.makeText(this, "Mobile 3G ", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "No Network ", Toast.LENGTH_LONG).show(); } } 

您可以使用以下方法每次检查networking状态:

 public static String checkNetworkStatus(final Context context) { String networkStatus = ""; // Get connect mangaer final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // check for wifi final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); // check for mobile data final android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if( wifi.isAvailable() ) { networkStatus = "wifi"; } else if( mobile.isAvailable() ) { networkStatus = "mobileData"; } else { networkStatus = "noNetwork"; } return networkStatus; } // end checkNetworkStatus 

// vKj

getNetworkInfo是一个不推荐的方法。 我build议使用getActiveNetworkInfo

 private String checkNetworkStatus(Context context) { String networkStatus =""; final ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); //Check Wifi final android.net.NetworkInfo wifi = manager.getActiveNetworkInfo(); //Check for mobile data final android.net.NetworkInfo mobile = manager.getActiveNetworkInfo(); if( wifi.getType() == ConnectivityManager.TYPE_WIFI) { networkStatus = "wifi"; }else if(mobile.getType() == ConnectivityManager.TYPE_MOBILE){ networkStatus = "mobileData"; }else{ networkStatus="noNetwork"; } return networkStatus; } 
  public boolean CheckConnectivity(final Context c) { ConnectivityManager mConnectivityManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE); if (mConnectivityManager.getActiveNetworkInfo() != null && mConnectivityManager.getActiveNetworkInfo().isAvailable() && mConnectivityManager.getActiveNetworkInfo().isConnected()) { return true; } else { return false; // make it false } }