如何检查定位服务是否启用?
我正在开发Android操作系统上的应用程序。 我不知道如何检查位置服务是否启用。
我需要一个方法,如果它们被启用则返回“true”,如果不是,则返回“false”(所以在最后的情况下,我可以显示一个对话框来启用它们)。
您可以使用下面的代码来检查是否启用gps提供商和networking提供商。
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(); }
我使用这个代码来检查:
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); } }
您可以使用此代码将用户引导至“设置”,以在其中启用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; }
根据上面的答案,在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); }
如果没有启用提供程序,则“被动”是返回的最佳提供程序。 请参阅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)); }
这个if子句很容易检查位置服务在我看来是否可用:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { //All location services are disabled }
我使用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; } }
正如Peter McClennan指出的那样,Google拥有一个与新的融合位置提供商非常协调的API。 在Github的Google示例代码中,一个完全有效的示例您不需要编写用户对话框来要求他们更改设置,因为它是通过API自动完成的。
是的,你可以检查下面的代码是:
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" />
要获取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(); } }
如果启用了Location services
,这是一个非常有用的方法,返回“ true
”:
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; }
您可以请求位置更新并一起显示对话框,例如GoogleMaps 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类。
要检查networking提供商,只需要将传递给isProviderEnabled的string更改为LocationManager.NETWORK_PROVIDER,如果您检查GPS提供商和networking提供商的返回值 – false都表示没有位置服务
private boolean isGpsEnabled() { LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE); return service.isProviderEnabled(LocationManager.GPS_PROVIDER)&&service.isProviderEnabled(LocationManager.NETWORK_PROVIDER); }