Como permitir o acesso à localização programaticamente no android?
estou a trabalhar na aplicação android relacionada com o mapa e preciso de verificar a opção Activar ou não o acesso à localização no desenvolvimento do lado do cliente se os Serviços de localização não estiverem a activar mostra a linha de comandos da janela.
Como activar o" acesso à localização " programaticamente no android?5 answers
Usar o código abaixo para verificar. Se estiver desactivado, será gerada uma janela
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();
}
Pode tentar estes métodos abaixo:
Para verificar se o GPS e o fornecedor da rede estão activos:
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;
}
Janela de alerta se o código acima devolve Falso:
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();
}
Como usar os dois métodos acima:
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();
}
Com a recente actualização do Marshmallow, mesmo quando a configuração da localização estiver activada, a sua aplicação irá necessitar de pedir explicitamente permissão. A forma recomendada para fazer isto é mostrar a secção de permissões da sua aplicação onde o utilizador pode comutar a permissão conforme necessário. O excerto do código para fazer isto é o seguinte:
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();
}
}
E sobrepor o método onRequestPermissionsResult
do seguinte modo:
@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);
}
}
}
}
Outra abordagem é que você também pode usar o SettingsApi para saber qual a localização os fornecedores estão activos. Se nenhum estiver activo, poderá pedir uma janela para alterar a configuração dentro da aplicação.
Serviços de localização.SettingsApi está desactualizado agora, por isso usamos SettingsClient