0

我有以下代码来检测是否有可用的互联网连接。但如果我没有互联网连接,只有数据连接是“开启”的,它仍然可以工作。我该做什么?

   ConnectivityManager cManager = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);


    NetworkInfo ninfo = cManager.getActiveNetworkInfo();


    if(ninfo!=null && ninfo.isConnected())

    {
      Toast.makeText(this, "Available",Toast.LENGTH_LONG).show();
    }

    else
    {
      Toast.makeText(this, "Not Available",Toast.LENGTH_LONG).show();
    }
4

2 回答 2

2

使用这个NetworkUtils类:

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetworkUtils {

  private static int TYPE_WIFI = 1;
  private static int TYPE_MOBILE = 2;
  private static int TYPE_NOT_CONNECTED = 0;

  public static int getConnectivityStatus(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context
        .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

    if (networkInfo != null) {
      if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI
          && networkInfo.getState() == NetworkInfo.State.CONNECTED) {

        return TYPE_WIFI;

      } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE
          && networkInfo.getState() == NetworkInfo.State.CONNECTED) {
        return TYPE_MOBILE;
      }
    }
    return TYPE_NOT_CONNECTED;
  }

  public static boolean isNetworkConnected(Context context) {
    int networkStatus = getConnectivityStatus(context);
    if (networkStatus == TYPE_WIFI || networkStatus == TYPE_MOBILE) {
      return true;
    } else {
      return false;
    }
  }
}

像这样使用:

if(NetworkUtils.isNetworkConnected(this)){

}
于 2017-02-21T04:25:40.640 回答
0

使用ConnectivityManager类。这是java类:

 ConnectivityManager manager =(ConnectivityManager) getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
 NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
        if (null != activeNetwork) {
            if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI){
                //we have WIFI
            }
            if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE){
                //we have cellular data
            }
        } else{
            //we have no connection :(
        }

不要忘记请求以下权限AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
于 2018-02-05T19:19:11.053 回答