如何在android中以编程方式启用位置访问?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25175522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to enable Location access programmatically in android?
提问by NarasimhaKolla
I am working on map related android application and I need to check location access enable or not in client side development if location services is not enable show the dialog prompt.
我正在开发与地图相关的 android 应用程序,如果未启用位置服务,我需要在客户端开发中检查位置访问是否启用显示对话框提示。
How to enable "Location access" Programmatically in android?
如何在android中以编程方式启用“位置访问”?
回答by Gautam
Use below code to check. If it is disabled, dialog box will be generated
使用以下代码进行检查。如果禁用,将生成对话框
public void statusCheck() {
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
}
}
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
回答by icaneatclouds
You can try these methods below:
您可以尝试以下这些方法:
To check if GPS and network provider is enabled:
要检查是否启用了 GPS 和网络提供商:
public boolean canGetLocation() {
boolean result = true;
LocationManager lm;
boolean gps_enabled = false;
boolean network_enabled = false;
if (lm == null)
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// exceptions will be thrown if provider is not permitted.
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 == false || network_enabled == false) {
result = false;
} else {
result = true;
}
return result;
}
Alert Dialog if the above code returns false:
如果上述代码返回 false,则警报对话框:
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
// Setting Dialog Title
alertDialog.setTitle("Error!");
// Setting Dialog Message
alertDialog.setMessage("Please ");
// On pressing Settings button
alertDialog.setPositiveButton(
getResources().getString(R.string.button_ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.show();
}
How to use the two methods above:
以上两种方法的使用方法:
if (canGetLocation() == true) {
//DO SOMETHING USEFUL HERE. ALL GPS PROVIDERS ARE CURRENTLY ENABLED
} else {
//SHOW OUR SETTINGS ALERT, AND LET THE USE TURN ON ALL THE GPS PROVIDERS
showSettingsAlert();
}
回答by schneiti
just checkout the following thread: How to check if Location Services are enabled?It provides a pretty good example of how to check whether the location service was enabled or not.
只需查看以下线程: 如何检查位置服务是否已启用?它提供了一个很好的示例,说明如何检查位置服务是否已启用。
回答by Mahendra Liya
With recent Marshmallow update, even when the Location setting is turned on, your app will require to explicitly ask for permission. The recommended way to do this is to show the Permissions section of your app wherein the user can toggle the permission as required. The code snippet for doing this is as below:
在最近的 Marshmallow 更新中,即使打开了位置设置,您的应用程序也需要明确请求许可。推荐的方法是显示应用程序的权限部分,用户可以在其中根据需要切换权限。执行此操作的代码片段如下:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {?
if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {?
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Location Permission");
builder.setMessage("The app needs location permissions. Please grant this permission to continue using the features of the app.");
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);?
}
});
builder.setNegativeButton(android.R.string.no, null);
builder.show();
}
} else {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean isGpsProviderEnabled, isNetworkProviderEnabled;
isGpsProviderEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkProviderEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGpsProviderEnabled && !isNetworkProviderEnabled) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Location Permission");
builder.setMessage("The app needs location permissions. Please grant this permission to continue using the features of the app.");
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
builder.setNegativeButton(android.R.string.no, null);
builder.show();
}
}
And override the onRequestPermissionsResult
method as below:
并覆盖onRequestPermissionsResult
方法如下:
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_COARSE_LOCATION: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "coarse location permission granted");
} else {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
}
}
}
Another approach is you can also use the SettingsApito inquire which location provider(s) are enabled. If none is enabled, you can prompt a dialog to change the setting from within the app.
另一种方法是您还可以使用SettingsApi来查询启用了哪些位置提供程序。如果未启用,您可以提示对话框以从应用程序内更改设置。
回答by makata
Here is a simple way of programmatically enabling location like Maps app:
这是一种以编程方式启用位置(如地图应用程序)的简单方法:
protected void enableLocationSettings() {
LocationRequest locationRequest = LocationRequest.create()
.setInterval(LOCATION_UPDATE_INTERVAL)
.setFastestInterval(LOCATION_UPDATE_FASTEST_INTERVAL)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
LocationServices
.getSettingsClient(this)
.checkLocationSettings(builder.build())
.addOnSuccessListener(this, (LocationSettingsResponse response) -> {
// startUpdatingLocation(...);
})
.addOnFailureListener(this, ex -> {
if (ex instanceof ResolvableApiException) {
// Location settings are NOT satisfied, but this can be fixed by showing the user a dialog.
try {
// Show the dialog by calling startResolutionForResult(), and check the result in onActivityResult().
ResolvableApiException resolvable = (ResolvableApiException) ex;
resolvable.startResolutionForResult(TrackingListActivity.this, REQUEST_CODE_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sendEx) {
// Ignore the error.
}
}
});
}
And onActivityResult:
和 onActivityResult:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (REQUEST_CODE_CHECK_SETTINGS == requestCode) {
if(Activity.RESULT_OK == resultCode){
//user clicked OK, you can startUpdatingLocation(...);
}else{
//user clicked cancel: informUserImportanceOfLocationAndPresentRequestAgain();
}
}
}
You can see the documentation here: https://developer.android.com/training/location/change-location-settings
您可以在此处查看文档:https: //developer.android.com/training/location/change-location-settings
回答by im-o
in AndroidManifest.xml add this :
在 AndroidManifest.xml 中添加:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
than in your activity, add this:
and call method checkPermissionMaps()
比在您的活动中,添加以下内容:
并调用方法 checkPermissionMaps()
private void checkPermissionMaps() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "checkMyPermissionMaps: Goto Execute OnMapReady");
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) {
if (permissions.length == 1 && permissions[0].equals(Manifest.permission.ACCESS_FINE_LOCATION) && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
//this call ur method u want load, exmp : zoomMyCuurentLocation();
} else {
finish(); // or call back checkPermissionMaps();
}
}
}