2012-04-25 87 views
158

我正在开发的Android操作系统的应用程序。我不知道如何检查定位服务是否启用。如何检查定位服务是否启用?

我需要的,如果他们被启用,“假”如果不是(所以在最后一种情况下我可以显示一个对话框,让他们)返回“真”的方法。

+1

我知道这是一个老话题,但对于那些谁可遵循...谷歌已经发布了这样的一个API;请参阅https://developers.google.com/android/reference/com/google/android/gms/location/SettingsApi – 2015-08-15 03:02:58

+0

[我在这里用代码回答类似的问题。](http://stackoverflow.com/questions/32423157/android-check-if-location-services-enabled-using-fused-location-provider/35753050?noredirect = 1#comment59185157_35753050)Check it out。很有帮助。 – 2016-03-02 19:16:44

回答

271

您可以使用下面的代码来检查GPS提供商和网络提供商是否启用。

LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE); 
boolean gps_enabled = false; 
boolean network_enabled = false; 

try { 
    gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); 
} catch(Exception ex) {} 

try { 
    network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
} catch(Exception ex) {} 

if(!gps_enabled && !network_enabled) { 
    // notify user 
    AlertDialog.Builder dialog = new AlertDialog.Builder(context); 
    dialog.setMessage(context.getResources().getString(R.string.gps_network_not_enabled)); 
    dialog.setPositiveButton(context.getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface paramDialogInterface, int paramInt) { 
       // TODO Auto-generated method stub 
       Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
       context.startActivity(myIntent); 
       //get gps 
      } 
     }); 
    dialog.setNegativeButton(context.getString(R.string.Cancel), new DialogInterface.OnClickListener() { 

      @Override 
      public void onClick(DialogInterface paramDialogInterface, int paramInt) { 
       // TODO Auto-generated method stub 

      } 
     }); 
    dialog.show();  
} 
+0

谢谢你的代码。检查位置管理器:'lm.getAllProviders()。contains(LocationManager.GPS_PROVIDER)'(或'NETWORK_PROVIDER')将确保您不会将用户引向没有网络选项的设置页面。 – petter 2013-11-16 16:32:51

+24

另外:'Settings.ACTION_SECURITY_SETTINGS'应该是'Settings.ACTION_LOCATION_SOURCE_SETTINGS'' – petter 2013-11-16 17:12:19

+2

如果手机处于“飞行模式”,这不起作用... – Accollativo 2014-07-14 15:10:45

26

您可以使用此代码来引导用户设置,在那里他们可以启用GPS:

locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); 
    if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { 
     AlertDialog.Builder builder = new AlertDialog.Builder(context); 
     builder.setTitle(R.string.gps_not_found_title); // GPS not found 
     builder.setMessage(R.string.gps_not_found_message); // Want to enable? 
     builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialogInterface, int i) { 
       owner.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); 
      } 
     }); 
     builder.setNegativeButton(R.string.no, null); 
     builder.create().show(); 
     return; 
    } 
+0

非常感谢,但我不需要代码来检查GPS,但只需定位服务。 – Meroelyth 2012-04-25 08:19:20

+1

位置服务始终可用,但不同的提供商可能不可用。 – lenik 2012-04-25 08:22:48

+3

@lenik,一些设备提供了一个设置(在“设置>个人>位置服务>访问我的位置”下),即使启用了特定提供程序,似乎也启用/禁用位置检测。我用我正在测试的手机看到了这个第一手资料,尽管Wifi和GPS都启用了,但他们似乎已经死了......我的应用程序。不幸的是,由于启用了设置,因此即使禁用了“访问我的位置”设置,也无法再生成原始方案。所以我不能说这个设置是否影响'isProviderEnabled()'和'getProviders(true)'方法。 – 2014-03-13 09:06:55

0

要检查网络供应商,你只需要改变传递给isProviderEnabled字符串,如果你检查返回值了GPS提供商和网络提供商LocationManager.NETWORK_PROVIDER - 无论是虚假的手段没有位置服务

5

这个if子句很容易检查位置服务在我看来是否可用:

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { 
     //All location services are disabled 

} 
5

如果没有提供者被启用,“被动”是返回的最佳提供者。 见https://stackoverflow.com/a/4519414/621690

public boolean isLocationServiceEnabled() { 
     LocationManager lm = (LocationManager) 
       this.getSystemService(Context.LOCATION_SERVICE); 
     String provider = lm.getBestProvider(new Criteria(), true); 
     return (StringUtils.isNotBlank(provider) && 
       !LocationManager.PASSIVE_PROVIDER.equals(provider)); 
    } 
196

我使用此代码检查:

public static boolean isLocationEnabled(Context context) { 
    int locationMode = 0; 
    String locationProviders; 

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){ 
     try { 
      locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE); 

     } catch (SettingNotFoundException e) { 
      e.printStackTrace(); 
      return false; 
     } 

     return locationMode != Settings.Secure.LOCATION_MODE_OFF; 

    }else{ 
     locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); 
     return !TextUtils.isEmpty(locationProviders); 
    } 


} 
+7

为了清楚起见,可能希望在catch块中返回false。否则,将locationMode初始化为Settings.Secure.LOCATION_MODE_OFF。 – RyanLeonard 2014-10-27 23:44:52

+0

对我而言,'locationProviders = Settings.Secure.getString(context.getContentResolver(),Settings.Secure.LOCATION_PROVIDERS_ALLOWED);'值为0,可能表示LOCATION_MODE_OFF? – 2015-03-10 05:15:08

+2

这是一个很好的答案,因为它适用于旧的和新的Android位置API。 – Diederik 2015-06-10 10:25:56

0
private boolean isGpsEnabled() 
{ 
    LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE); 
    return service.isProviderEnabled(LocationManager.GPS_PROVIDER)&&service.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
} 
2

要获得谷歌Android地图当前地理位置,你应开启装置的位置选项。要检查位置是否打开,您可以简单地从您的onCreate()方法调用此方法。

private void checkGPSStatus() { 
    LocationManager locationManager = null; 
    boolean gps_enabled = false; 
    boolean network_enabled = false; 
    if (locationManager == null) { 
     locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    } 
    try { 
     gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
    } catch (Exception ex){} 
    try { 
     network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
    } catch (Exception ex){} 
    if (!gps_enabled && !network_enabled){ 
     AlertDialog.Builder dialog = new AlertDialog.Builder(MyActivity.this); 
     dialog.setMessage("GPS not enabled"); 
     dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 

      @Override 
      public void onClick(DialogInterface dialog, int which) { 
       //this will navigate user to the device location settings screen 
       Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
       startActivity(intent); 
      } 
     }); 
     AlertDialog alert = dialog.create(); 
     alert.show(); 
    } 
} 
5

是的,你可以看看下面的代码:

public boolean isGPSEnabled(Context mContext) 
{ 
    LocationManager lm = (LocationManager) 
    mContext.getSystemService(Context.LOCATION_SERVICE); 
    return lm.isProviderEnabled(LocationManager.GPS_PROVIDER); 
} 

与清单文件的权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
3

我用这样的方式为NETWORK_PROVIDER但您可以添加并为GPS

LocationManager locationManager; 

的onCreate我把

isLocationEnabled(); 
    if(!isLocationEnabled()) { 
     AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 
     builder.setTitle(R.string.network_not_enabled) 
       .setMessage(R.string.open_location_settings) 
       .setPositiveButton(R.string.yes, 
         new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, int id) { 
           startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); 
          } 
         }) 
       .setNegativeButton(R.string.cancel, 
         new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, int id) { 
           dialog.cancel(); 
          } 
         }); 
     AlertDialog alert = builder.create(); 
     alert.show(); 
    } 

而且检查

protected boolean isLocationEnabled(){ 
    String le = Context.LOCATION_SERVICE; 
    locationManager = (LocationManager) getSystemService(le); 
    if(!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){ 
     return false; 
    } else { 
     return true; 
    } 
} 
+0

你不需要if-then-else,你可以返回'locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); ' – LadyWoodi 2017-02-14 13:18:50

4

彼得McClennan指示的方法,谷歌已经与新融合位置提供运作非常良好的API 。一个完全工作的例子是在 Google Sample Code at Github你不需要代码的用户对话框,问他们,因为它是用API自动完成更改设置。

+0

你的链接是404,这就是为什么堆栈溢出建议不要链接 – edthethird 2017-07-18 15:53:36

2

这是返回一个非常有用的方法“true”如果Location services已启用:

public static boolean locationServicesEnabled(Context context) { 
     LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); 
     boolean gps_enabled = false; 
     boolean net_enabled = false; 

     try { 
      gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); 
     } catch (Exception ex) { 
      Log.e(TAG,"Exception gps_enabled"); 
     } 

     try { 
      net_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
     } catch (Exception ex) { 
      Log.e(TAG,"Exception network_enabled"); 
     } 
     return gps_enabled || net_enabled; 
} 
2

可以请求位置更新和显示对话框在一起,像Google地图DOAS也。这里是代码:

googleApiClient = new GoogleApiClient.Builder(getActivity()) 
       .addApi(LocationServices.API) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this).build(); 
googleApiClient.connect(); 

LocationRequest locationRequest = LocationRequest.create(); 
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
locationRequest.setInterval(30 * 1000); 
locationRequest.setFastestInterval(5 * 1000); 
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() 
        .addLocationRequest(locationRequest); 

builder.setAlwaysShow(true); //this is the key ingredient 

PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build()); 
result.setResultCallback(new ResultCallback<LocationSettingsResult>() { 
    @Override 
    public void onResult(LocationSettingsResult result) { 
     final Status status = result.getStatus(); 
     final LocationSettingsStates state = result.getLocationSettingsStates(); 
     switch (status.getStatusCode()) { 
      case LocationSettingsStatusCodes.SUCCESS: 
       // All location settings are satisfied. The client can initialize location 
       // requests here. 
       break; 
      case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: 
       // Location settings are not satisfied. But could be fixed by showing the user 
       // a dialog. 
       try { 
        // Show the dialog by calling startResolutionForResult(), 
        // and check the result in onActivityResult(). 
        status.startResolutionForResult(getActivity(), 1000); 
       } catch (IntentSender.SendIntentException ignored) {} 
       break; 
      case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: 
       // Location settings are not satisfied. However, we have no way to fix the 
       // settings so we won't show the dialog. 
       break; 
      } 
     } 
    }); 
} 

如果您需要更多信息请检查LocationRequest类。

+0

你好,我一直在挣扎,因为最近两天得到用户的当前位置。我需要当前经纬度的用户,我知道可以使用谷歌API客户端完成。但如何将棉花糖许可纳入其中。此外,如果用户的位置服务已关闭,如何启用它。你能帮我吗? – Chetna 2016-09-05 05:52:40

+0

嗨!你有很多问题,我在评论中无法回答。请提出一个新问题,以便我可以更正式地回答它! – bendaf 2016-09-05 08:45:04

+0

我已经在这里发布我的问题:http://stackoverflow.com/questions/39327480/how-to-get-users-current-location-in-android – Chetna 2016-09-05 09:23:38

10

工作过上面的答案,在API 23,你需要添加“危险”的权限检查以及检查系统的本身:

public static boolean isLocationServicesAvailable(Context context) { 
    int locationMode = 0; 
    String locationProviders; 
    boolean isAvailable = false; 

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){ 
     try { 
      locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE); 
     } catch (Settings.SettingNotFoundException e) { 
      e.printStackTrace(); 
     } 

     isAvailable = (locationMode != Settings.Secure.LOCATION_MODE_OFF); 
    } else { 
     locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); 
     isAvailable = !TextUtils.isEmpty(locationProviders); 
    } 

    boolean coarsePermissionCheck = (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED); 
    boolean finePermissionCheck = (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED); 

    return isAvailable && (coarsePermissionCheck || finePermissionCheck); 
} 
+0

无法解析符号Manifest.permission.ACCESS_COARSE_LOCATION和Manifest.permission.ACCESS_FINE_LOCATION – 2016-07-25 08:34:20

+0

使用android.Manifest.permission.ACCESS_FINE_LOCATION – aLIEz 2016-11-18 13:39:02

0

我先用代码开始创建方法isLocationEnabled

private LocationManager locationManager ; 

protected boolean isLocationEnabled(){ 
     String le = Context.LOCATION_SERVICE; 
     locationManager = (LocationManager) getSystemService(le); 
     if(!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){ 
      return false; 
     } else { 
      return true; 
     } 
    } 

和我检查条件,如果自命打开地图和虚假给予意图ACTION_LOCATION_SOURCE_SETTINGS

if (isLocationEnabled()) { 
     SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
       .findFragmentById(R.id.map); 
     mapFragment.getMapAsync(this); 

     locationClient = getFusedLocationProviderClient(this); 
     locationClient.getLastLocation() 
       .addOnSuccessListener(new OnSuccessListener<Location>() { 
        @Override 
        public void onSuccess(Location location) { 
         // GPS location can be null if GPS is switched off 
         if (location != null) { 
          onLocationChanged(location); 

          Log.e("location", String.valueOf(location.getLongitude())); 
         } 
        } 
       }) 
       .addOnFailureListener(new OnFailureListener() { 
        @Override 
        public void onFailure(@NonNull Exception e) { 
         Log.e("MapDemoActivity", e.toString()); 
         e.printStackTrace(); 
        } 
       }); 


     startLocationUpdates(); 

    } 
    else { 
     new AlertDialog.Builder(this) 
       .setTitle("Please activate location") 
       .setMessage("Click ok to goto settings else exit.") 
       .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int which) { 
         Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
         startActivity(intent); 
        } 
       }) 
       .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int which) { 
         System.exit(0); 
        } 
       }) 
       .show(); 
    } 

enter image description here

相关问题