【问题标题】:Network State Finding Issue with ConnectivityManager in androidandroid 中 ConnectivityManager 的网络状态查找问题
【发布时间】:2018-05-28 07:09:14
【问题描述】:

我想查找此手机是否已连接互联网(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 {
}

【问题讨论】:

    标签: android android-networking network-connection android-connectivitymanager


    【解决方案1】:

    试试这个,

    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;
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-23
      • 2019-07-02
      • 1970-01-01
      相关资源
      最近更新 更多