简体   繁体   English

如何以编程方式检查Android上是否启用了“使用无线网络”?

[英]How to check programmatically if “use wireless networks” is enabled on Android?

I don't want to check if there is any connectivity over WIFI or 3G! 我不想检查WIFI或3G是否有任何连接! I just want to verify (and not change!) if the "Use wireless networks"-CheckBox is enabled (the one you can set in Settings > Location and security > My location > HERE) Thanx 我只想验证(不要更改!)是否启用了“使用无线网络”复选框(您可以在“设置”>“位置和安全性”>“我的位置”>“此处”中设置)

Code from RajaReddy will check if Wifi is enabled for network. 来自RajaReddy的代码将检查是否为网络启用了Wifi。 If you want to know if Wifi is enabled for positioning then this should do (replace "context" with something useful) 如果您想知道是否已启用Wifi定位功能,则应该这样做(将“上下文”替换为有用的内容)

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

example code for API Level < 8 API级别<8的示例代码

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

use this code 使用此代码

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

and following permissions are required for this 并且为此需要以下权限

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM