【问题标题】:How to check programmatically if "use wireless networks" is enabled on Android?如果在 Android 上启用了“使用无线网络”,如何以编程方式检查?
【发布时间】:2012-02-15 10:49:48
【问题描述】:

我不想检查是否有任何通过 WIFI 或 3G 的连接! 我只想验证(而不是更改!)“使用无线网络”复选框是否已启用(您可以在“设置”>“位置和安全”>“我的位置”>“此处”中设置该复选框) 谢谢

【问题讨论】:

    标签: java android connection wifi


    【解决方案1】:

    来自 RajaReddy 的代码将检查是否为网络启用了 Wifi。如果您想知道是否启用了 Wifi 进行定位,那么应该这样做(将“上下文”替换为有用的内容)

    ContentResolver cr = context.getContentResolver();
    boolean wifiEnabled = Settings.Secure.isLocationProviderEnabled(cr, LocationManager.NETWORK_PROVIDER);
    

    API 级别

    private static boolean isWifiLocationEnabled (Context context) {
        ContentResolver cr = context.getContentResolver();
        String enabledProviders = Settings.Secure.getString(cr, Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if (!TextUtils.isEmpty(enabledProviders)) {
            // not the fastest way to do that :)
            String[] providersList = TextUtils.split(enabledProviders, ",");
            for (String provider : providersList) {
                if (LocationManager.NETWORK_PROVIDER.equals(provider)) {
                    return true;
                }
            }
        }
        return false;
    }
    

    【讨论】:

    • 我在 Settings.Secure 中没有 isLocationProviderEnabled 方法。我能以某种方式访问​​它吗?
    • 好的,该方法是 API 8 级及以上。 String allowedProviders = Settings.Secure.getString(cr, Settings.Secure.LOCATION_PROVIDERS_ALLOWED); 应该为您提供一个逗号分隔的已启用提供程序列表,您可以在其中查找 LocationManager.NETWORK_PROVIDER
    • 就是这样!当启用“使用 GPS 卫星”和“使用无线网络”这两个选项时,该列表包含“网络,gps”。你让我开心!
    【解决方案2】:

    使用此代码

    public Boolean isNetAvailable(Context con) {
    
       try {
          ConnectivityManager connectivityManager = (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE);
          NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    
          if(wifiInfo.isConnected()) {
             return true;
          }
       }catch(Exception e){
          e.printStackTrace();
       }
       return false;
    }
    

    此操作需要以下权限

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission> 
    

    【讨论】:

    • 这很好用,但如果用户在他的 android-settings 中选中了“使用无线网络”,我仍然无法找到这种方式。上面的代码只是检查是否有 WIFI/网络连接......这不是我想要的。自卫队
    猜你喜欢
    • 2012-06-23
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 2011-03-31
    • 1970-01-01
    • 2011-03-07
    相关资源
    最近更新 更多