【问题标题】:Check network connection with LocationManager in Android在 Android 中使用 LocationManager 检查网络连接
【发布时间】:2013-08-30 11:52:24
【问题描述】:

我想用 Android 中的 LocationManager 检查网络连接。 我的代码适用于 Galaxy SII 和 4.0.3 版。 但它不适用于 Galaxy S 和 2.3.6 版。

代码:

 isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
 isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

我肯定已连接到 Wi-Fi 网络。但是if语句

if (!isGPSEnabled && !isNetworkEnabled)

返回真。是否存在已知错误,是否有可靠的检查方法?

【问题讨论】:

  • 位置提供者和网络connectivity 是不同的东西。一个告诉您用户是否在系统设置中启用了 gps / 网络位置跟踪,另一个告诉您您是否已连接到互联网。

标签: android networking gps connection location


【解决方案1】:

试试这个:

    //If you only want to check your Internet connection available or not    
        public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
                        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                        return activeNetworkInfo != null && activeNetworkInfo.isConnected();}

注意wifiInfo 为您提供有关 Wifi 的状态,但仍然会出现连接不佳的情况,我认为如果进行 HTTP reuest 会很好strong>,有关详细信息,请查看提供的链接。

编辑: 有关更多信息,您可以[参考此][1]。

【讨论】:

    【解决方案2】:

    我在每个 android 项目中都使用下面的代码。 它将检查用于传出连接的任何活动网络。

    public static boolean isNetworkAvailable(Context context)
        {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    
            if (networkInfo != null && networkInfo.isConnectedOrConnecting())
                return true;
    
            return false;
        }
    

    【讨论】:

      【解决方案3】:

      使用此代码:

       public static boolean checkConn(Context ctx)
      {
      
          ConnectivityManager conMgr =  (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
      
          NetworkInfo wifiInfo = conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
          NetworkInfo mobileInfo = conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);    
          NetworkInfo info = conMgr.getActiveNetworkInfo();
      
          if(info != null && info.isConnected()) {  
              Log.v("NetworkInfo","Connected State");  
              return true;
          }  
          return false;
      }
      

      【讨论】:

        猜你喜欢
        • 2012-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-05
        • 1970-01-01
        • 2017-05-23
        • 1970-01-01
        相关资源
        最近更新 更多