1

我想找到这个手机是否连接互联网(wifi 和移动数据)我使用下面的代码它在所有设备上都可以正常工作,除了一个 mi note 4 我发现一个问题,当它没有与互联网连接时它没有显示错误请帮助我.

  public class ConnectionDetector {
  private Context _context;

  public ConnectionDetector(Context context)
  {
    this._context = context;
  }

public boolean isConnectingToInternet()
{
    ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivity != null)
    {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++)
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
        }
    }
    return false;
}
}

ConnectionDetector cd = new ConnectionDetector(ViewOrder.this);
Boolean isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
           // its giving true when its in offline only in mi note 4 device. all the mobiles which i checked its working fine
}
else {
}
4

1 回答 1

0

尝试这个,

public class NetworkUtility {

/**
 * Provides whether internet is connected or not
 * @param context
 * @return true if connected , 
 * else false
 */
public static boolean isInternetOn(Context context) {
    if (context == null) 
        return false;

        ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = conn.getActiveNetworkInfo();
        if (networkInfo != null) {
            return networkInfo.isConnected();
        }

    return false;
}
}
于 2018-05-28T07:25:32.100 回答