How can i know if user DENIED permission for GPS android - android

here is my code and it asks me for permission if i click Allow it works good but when the user clicks on DENY i want to get a result or log for denied
if user clicks "DENY" permission how can i set something on that
here is my code :
LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Location location;
if (network_enabled) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
;
}
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION},
1);
location = locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!=null){
lat = location.getLongitude();
lon = location.getLatitude();
Log.d("lat", "onCreate: "+lat+","+lon);
txtLocation.setText(+lat+","+lon);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Latitude:"+lat+"\n"+"Longitude:"+lon);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
Log.d("", "onRequestPermissionsResult: "+requestCode);
Toast.makeText(MainActivity.this, ""+grantResults.length, Toast.LENGTH_SHORT).show();
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "Granted", Toast.LENGTH_SHORT).show();
// permission was granted, yay! Do the
} else {
Toast.makeText(MainActivity.this, "Denied", Toast.LENGTH_SHORT).show();
//user denied permission additionally you can check
//ActivityCompat.shouldShowRequestPermissionRationale if user checked on "do not show again" while clicking deny
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}

First implement an onRequestPermissionResult like this:
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_ACCESS_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
} else {
//user denied permission additionally you can check
//ActivityCompat.shouldShowRequestPermissionRationale if user checked on "do not show again" while clicking deny
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}

Related

I can't access GPS using Android 10 (API 29)

I use a code that worked fine with Android 4.1. But this code doesn't work any more with Android 10. The code is as follows :
LocationManager Objgps = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Objlistener = new GPSlistener();
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return;
}
Objgps.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, Objlistener);
and :
private class GPSlistener implements LocationListener {
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onLocationChanged(Location location) {
Latitude.setText(CoordHrzSoleil.DDecToDMS(location.getLatitude()));
}
}
and within the manifest :
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
It seems that it misses some extra permissions, but I don't know what they are and how to apply them.
Thank you for your help.
Pierre.
Well, finally, I found the (or a) solution ; it's the same kind of gymnastics as for writing / reading files:
In the manifest you must :
<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_BACKGROUND_LOCATION"/>"
Then, in the code :
if (Build.VERSION.SDK_INT >= 23) {
if (checkPermission()) {
} else {
requestPermission(); // Code for permission
}
}
...
private boolean checkPermission() {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)
&& ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION)) {
Toast.makeText(MainActivity.this, "Access fine and coarse location allows us to use GPS. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, GPS_PERMISSION_REQUEST);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, GPS_PERMISSION_REQUEST);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case GPS_PERMISSION_REQUEST:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e("value", "Permission Granted, Now you can use GPS .");
} else {
Log.e("value", "Permission Denied, You cannot use GPS .");
}
break;
}
}
I haven't granted permission for "ACCESS_BACKGROUND_LOCATION". I'll have to check if it's necessary.
Cordially.
Pierre.

Google map location permission does not show up for Android version 8+ Android developement

Google maps permission does not pop up for Android version 8+. For Android 5, it works fine.
The permission should pop up like the following picture, but it doesn't show on Android version 8+
Now, I know it has something to do with run-time permission. I added related code, but the app stops after I grant the permission.
What have I done wrong?
These are all the permissions granted.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
This is the code in onCreate()
if (!checkPermission()) {
requestPermission();
}
These are code related to permission checking and granting
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(), ACCESS_FINE_LOCATION);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), ACCESS_COARSE_LOCATION);
return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_CODE);
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0) {
boolean fineLocationAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean coarseLocationAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (!(fineLocationAccepted && coarseLocationAccepted)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION)) {
showMessageOKCancel("You need to allow access to both the permissions",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION},
PERMISSION_REQUEST_CODE);
}
}
});
return;
}
}
}
}
break;
}
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
But the app crashes after I click on "allow".
Error messages
2019-05-01 23:46:17.257 4519-16175/? E/PhenotypeFlagCommitter: Retrieving snapshot for com.google.android.gms.playlog.uploader failed
java.lang.InterruptedException
at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedNanos(AbstractQueuedSynchronizer.java:1063)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.tryAcquireSharedNanos(AbstractQueuedSynchronizer.java:1352)
at java.util.concurrent.CountDownLatch.await(CountDownLatch.java:278)
at asip.a(:com.google.android.gms#16091022#16.0.91 (040700-244116403):27)
at alhm.a(:com.google.android.gms#16091022#16.0.91 (040700-244116403):2)
at alhm.a(:com.google.android.gms#16091022#16.0.91 (040700-244116403):19)
at alhm.a(:com.google.android.gms#16091022#16.0.91 (040700-244116403):29)
at com.google.android.gms.clearcut.uploader.QosUploaderChimeraService.d(:com.google.android.gms#16091022#16.0.91 (040700-244116403):3)
at com.google.android.gms.clearcut.uploader.QosUploaderChimeraService.a(:com.google.android.gms#16091022#16.0.91 (040700-244116403):14)
at com.google.android.gms.clearcut.uploader.QosUploaderChimeraService.a(:com.google.android.gms#16091022#16.0.91 (040700-244116403):6)
at zse.run(:com.google.android.gms#16091022#16.0.91 (040700-244116403):5)
at rrt.b(:com.google.android.gms#16091022#16.0.91 (040700-244116403):32)
at rrt.run(:com.google.android.gms#16091022#16.0.91 (040700-244116403):21)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at rxx.run(Unknown Source:7)
at java.lang.Thread.run(Thread.java:764)
Here is what I did
private void askForPermission(String permission, Integer requestCode) {
if (ContextCompat.checkSelfPermission(Main2Activity.this, permission) != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(Main2Activity.this, permission)) {
//This is called if user has denied the permission before
//In this case I am just asking the permission again
ActivityCompat.requestPermissions(Main2Activity.this, new String[]{permission}, requestCode);
} else {
deviceSetting(getApplicationContext());
ActivityCompat.requestPermissions(Main2Activity.this, new String[]{permission}, requestCode);
}
} else {
deviceSetting(getApplicationContext());
Toast.makeText(this, "" + permission + " is already granted.", Toast.LENGTH_SHORT).show();
}
}
private void deviceSetting(Context context) {
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API).build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(10000 / 2);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
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();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Log.e("tag", "All location settings are satisfied.");
startLocationUpdates();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Log.e("tag", "Location settings are not satisfied. Show the user a dialog to upgrade location settings ");
try {
// Show the dialog by calling startResolutionForResult(), and check the result
// in onActivityResult().
status.startResolutionForResult(Main2Activity.this, REQUEST_PERMISSIONS_LOCATION_SETTINGS_REQUEST_CODE);
} catch (IntentSender.SendIntentException e) {
Log.e("tag", "PendingIntent unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.e(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog not created.");
break;
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (ActivityCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
deviceSetting(getApplicationContext());
} else {
saveData(latitude, longitude, "no");
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("onActivityResult()", Integer.toString(resultCode));
//final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
switch (requestCode) {
case REQUEST_PERMISSIONS_LOCATION_SETTINGS_REQUEST_CODE:
switch (resultCode) {
case Activity.RESULT_OK: {
// All required changes were successfully made
Toast.makeText(getApplicationContext(), "Location enabled by user!", Toast.LENGTH_LONG).show();
startLocationUpdates();
break;
}
case Activity.RESULT_CANCELED: {
// The user was asked to change settings, but chose not to
Toast.makeText(getApplicationContext(), "Location not enabled, user cancelled.", Toast.LENGTH_LONG).show();
break;
}
default: {
break;
}
}
break;
}
}
protected void startLocationUpdates() {
Log.e("inside", "startlocationupdate");
// Create the location request to start receiving updates
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// mLocationRequest.setInterval(UPDATE_INTERVAL);
/// mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
// Create LocationSettingsRequest object using location request
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
LocationSettingsRequest locationSettingsRequest = builder.build();
Log.e("locationsettingsreuqest", String.valueOf(locationSettingsRequest));
// Check whether location settings are satisfied
// https://developers.google.com/android/reference/com/google/android/gms/location/SettingsClient
SettingsClient settingsClient = LocationServices.getSettingsClient(Main2Activity.this);
settingsClient.checkLocationSettings(locationSettingsRequest);
Log.e("locationsettingsreuqest", String.valueOf(settingsClient));
// new Google API SDK v11 uses getFusedLocationProviderClient(this)
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details
return;
}
LocationServices.getFusedLocationProviderClient(getApplicationContext()).requestLocationUpdates(mLocationRequest, new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
onLocationChanged(locationResult.getLastLocation());
}
},
Looper.myLooper());
}
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
I hope it works otherwise let me know

Error in startlocation update in request permissions

i have an error that i cant fix and when i press alt+enter nothing
happens, i already added permission.ACCESS_FINE_LOCATION etc in the
manifest, can someone please help me ? i tried everything but nothing
seems to work
private void startLocationUpdates(){
String[] PERMISSIONS = {android.Manifest.permission.ACCESS_FINE_LOCATION,android.Manifest.permission.ACCESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(this, PERMISSIONS[0])
!= PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, PERMISSIONS[1])
!= PackageManager.PERMISSION_GRANTED
) {
//gives me error in this activity.compat.request
ActivityCompat.requestPermissions((Activity) this, PERMISSIONS, 0 );
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);// and error in this line too
Toast.makeText(this, "sinal pedido", Toast.LENGTH_SHORT).show();
}
}
Try this
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle(R.string.title_location_permission)
.setMessage(R.string.text_location_permission)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Request location updates:
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
}
}
Then you would just modify your onResume() override to call checkLocationPermission():
#Override
protected void onResume() {
super.onResume();
if (checkLocationPermission()) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Request location updates:
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
}
}
Source: this

cannot fetch location in marshmallow after giving permission request

I am developing an location app which is working fine in all devices except in Marshmallow.I have requested permission during runtime and when I grant permission longitude and latitude is not fetched,if i go to settings and change the location from high accuracy to battery saving,location is fetched and the app works.I want location to be fetched at high accuracy.
ActivityCompat.requestPermissions(this,
new String[]{
Manifest.permission.CAMERA,
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_WIFI_STATE,
Manifest.permission.INTERNET,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.WAKE_LOCK,
},
1);
try this
step 1 :- add this permission in manifiesr file
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION,
step 2 : ask runtime permission
String permission = android.Manifest.permission.ACCESS_FINE_LOCATION;
if (ActivityCompat.checkSelfPermission(SearchCityClass.this, permission)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.
checkSelfPermission(SearchCityClass.this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(SearchCityClass.this, new String[]
{permission}, PERMISSION_GPS_CODE);
}
step 3: handle permsiion result
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_GPS_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, location_permission_granted_msg, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, location_permission_not_granted_msg, Toast.LENGTH_SHORT).show();
}
}
}
You have to give run time permission for android 6 like this
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
// Permission already Granted
//Do your work here
//Perform operations here only which requires permission
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
and if permission is not already granted override onRequestPermission Results like this
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Permission Granted
//Do your work here
//Perform operations here only which requires permission
}
}
}
Add this code your Activity class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_images);
requestLocationPermission();
//your other codes
}
private void requestLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
} else {
ActivityCompat.requestPermissions(this, new String[]
{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
//If permission is granted
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can get the location", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
Add this on your Mainfest XML
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

How to turn on Location in lollipop or up version and get current location

I try to turn on gps location in lollipop device(not emulator).I wrote real time permission code,but not working correct.This is my source:
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (ActivityCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_GRANTED) {
askForGPS();
Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
private void askForGPS(){
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(30 * 1000);
mLocationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
result = LocationServices.SettingsApi.checkLocationSettings(client, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(MainActivity.this, GPS_SETTINGS);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
}
private void askForPermission(String permission, Integer requestCode) {
if (ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permission)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
}
} else {
Toast.makeText(this, "" + permission + " is already granted.", Toast.LENGTH_SHORT).show();
}
}
In button click i try to ask permission like this.
askForPermission(Manifest.permission.ACCESS_FINE_LOCATION,LOCATION);
When i run my app ,i can't show alertDialog and can't turn on location .I don't know but program showing this Toast message "is already granted."
My askForPermission method not working correct.My question is that how i can turn on GPS with real time permission and get current location?
public void getCurrenctLocation(Location location)
{
Log.e("Current lang", location.getLatitude()+"");
Log.e("Current long", location.getLongitude()+"");
}
How and where i can use my getCurrenctLocation method?
thank
1) Modify your askForPermission() like this:
private void askForPermission(String permission, Integer requestCode) {
if (ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
} else {
askForGPS();
}
}
2) Modify onRequePermissionResult() like below:
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case LOCATION: //You have to declare LOCATION globally. example: private int LOCATION = 1 ;
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission Granted
askForGPS();
Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
}
else {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permissions[0])) {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permission denied permanently, please go to app settings to grant permission.", Toast.LENGTH_SHORT).show();
}
}
break;
}
}

Categories

Resources