Android Background Location Permissions - android

While asking for location permission in the background, it keeps asking me to open the settings menu and allow it, even though I say allow only this time. (Android 11)
I want to get permission on my login activity's init function.
I just don't want it to ask for permission again when I select only this time and start the app again.
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED) {
} else {
askPermissionForBackgroundUsage();
}
}
} else {
askForLocationPermission();
}
}
private void askForLocationPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(this)
.setTitle("Permission Needed!")
.setMessage("Location Permission Needed!")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(LoginActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 101);
}
})
.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Permission is denied by the user
}
})
.create().show();
} else {
ActivityCompat.requestPermissions(this,
new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
}, 101);
}
}
private void askPermissionForBackgroundUsage() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION)) {
new AlertDialog.Builder(this)
.setTitle("Permission Needed!")
.setMessage("Background Location Permission Needed!, tap \"Allow all time in the next screen\"")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(LoginActivity.this,
new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION}, 101);
}
})
.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// User declined for Background Location Permission.
}
})
.create().show();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION}, 101);
}
}

Related

Getting location and external storage permissions in one application session in Android

I am adding Location and ExternalWrite permissions to my application. I would like for users to be able to acquire both permissions in one application session. Currently the application must be closed and reopened for the external write permission request dialog to appear.
Code in MainActivity is as follows,
public boolean checkExternalWritePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
new AlertDialog.Builder(this)
.setTitle(R.string.title_externalwrite_permission)
.setMessage(R.string.text_externalwrite_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.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_EXTERNAL_WRITE);
}
})
.create()
.show();
} else {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},MY_PERMISSIONS_REQUEST_EXTERNAL_WRITE);
}
return false;
} else {
return true;
}
}
...and
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
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) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
However, calling these from OnCreate,
#Override
protected void onCreate(Bundle savedInstanceState) {
...
checkLocationPermission();
checkExternalWritePermission()
}
after a fresh install (or a permissions reset) results in only the first function in OnCreate being called. The second is not called without the application being closed and restarted. Question: How can I get both permissions granted in one application session? Thanks in advance.
This works.
private boolean requestPermissions() {
int iExtStorage = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
int iCoarseLocation = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION);
int iFineLocation = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION);
List<String> listPermissionsNeeded = new ArrayList<>();
if (iExtStorage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (iFineLocation != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
}
if (iCoarseLocation != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
}
if (!listPermissionsNeeded.isEmpty())
{
ActivityCompat.requestPermissions(this,listPermissionsNeeded.toArray
(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}

Multiple permissions and ask again on denial

I want to make an app which asks user for two permissions- READ_CALL_LOG and READ_CONTACTS. Now if the user denies READ_CALL_LOG then it should show a warning which should have a button that asks the user to grant permission again. When that button is clicked the user is asked again to grant READ_CALL_LOG permission. When the user grants READ_CALL_LOG permission he is taken to READ_CONTACTS permission. If he denies READ_CONTACTS permission then again it should show a warning which should have a button that asks the user to grant permission again. When that button is clicked the user is asked again to grant READ_CONTACTS permission. I don't want the user to be navigated to Settings if he denies. I have tried this code:
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*if(((ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.READ_CALL_LOG)== PackageManager.PERMISSION_DENIED)&&(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.READ_CONTACTS)== PackageManager.PERMISSION_DENIED))||((ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.READ_CALL_LOG)!= PackageManager.PERMISSION_GRANTED)&&(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED)))
requestPermission();*/
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.READ_CALL_LOG)== PackageManager.PERMISSION_DENIED)
{
requestCallLogsPermission();
}
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.READ_CONTACTS)== PackageManager.PERMISSION_DENIED)
{
requestContactPermission();
}
}
private void requestCallLogsPermission()
{
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.READ_CALL_LOG)!= PackageManager.PERMISSION_GRANTED)
{
Dexter.withActivity(MainActivity.this).withPermission(Manifest.permission.READ_CALL_LOG).withListener(new PermissionListener()
{
#Override
public void onPermissionGranted(PermissionGrantedResponse response)
{
Toast.makeText(MainActivity.this, "Call Logs Permission is granted !", Toast.LENGTH_SHORT).show();
//if((ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.READ_CONTACTS)== PackageManager.PERMISSION_DENIED)||ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED)
requestContactPermission();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response)
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Permissions");
builder.setMessage("Permission is required");
builder.setCancelable(false);
builder.setPositiveButton("Understood, I am ready to give the permissions required", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
requestCallLogsPermission();
}
}).show();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
}
private void requestContactPermission()
{
Dexter.withActivity(MainActivity.this).withPermission(Manifest.permission.READ_CONTACTS).withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
Toast.makeText(MainActivity.this, "Read Contacts Permission is granted !", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Permissions");
builder.setMessage("Permission is required");
builder.setCancelable(false);
builder.setPositiveButton("Understood, I am ready to give the permissions required", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
requestCallLogsPermission();
}
}).show();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
token.continuePermissionRequest();
}
}).check();
}
}
You can try this method:
1.) Setting up permissions:
String[] permissions = {
android.Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.CAMERA
}; // Use the permission you need
2.) -Check and request if not already permitted:
onCreate() {
if (!checkPermissions()){
ActivityCompat.requestPermissions(this, permissions, 1);
}
}
private boolean checkPermissions() {
for (String permission: permissions){
if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED){
return false;
}
}
return true;
}
3.) Check for denial status and keep asking till all permissions are granted:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
boolean allGranted = true;
for (int result: grantResults){
if (result == PackageManager.PERMISSION_DENIED){
allGranted = false;
}
}
if (!allGranted){
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) ||
ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE))
{
// Here do whatever you want once the user denies
final String[] mPermissions = permissions;
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert!");
alertDialog.setMessage("Please allow the permissions!");
alertDialog.setCancelable(false);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((MainActivity.this), mPermissions, 1);
dialog.dismiss();
}
});
alertDialog.show();
}
else {
Log.d(TAG, "PERMANENTLY DENIED");
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert!");
alertDialog.setMessage("All permissions are necessary for app to run. Goto settings and grant them.");
alertDialog.setCancelable(false);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + BuildConfig.APPLICATION_ID)));
dialog.dismiss();
}
});
alertDialog.show();
}
}
}

Runtime Location Permission Issue in Android 10

I am building an app where I need to implement a Google Map API. In all the android versions app is working as expected but in SDK 29 or android 10 it is not working. Every time I grant location permission it again ask for the location permission, I have even manually grant the permission but still, it's not working. Here is my code:
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("Grant Permission")
.setMessage("Location Permission Required")
.setPositiveButton("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;
}
}
I am calling this method in onCreate in an activity.
1) In menifest
<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_BACKGROUND_LOCATION" />
2) Inside Activity
I) Define globally inside activity
private static final int PERMISSION_CALLBACK_CONSTANT = 105;
private SharedPreferences permissionStatus;
String[] permissionsRequired = new String[]{
Manifest.permission.ACCESS_FINE_LOCATION
, Manifest.permission.ACCESS_COARSE_LOCATION
, Manifest.permission.ACCESS_BACKGROUND_LOCATION
};
II)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
permissionStatus = getSharedPreferences("permissionStatus", MODE_PRIVATE);
checkPermission();
}
III) Create a method
public void checkPermission() {
if (ActivityCompat.checkSelfPermission(BaseMapActivity.this, permissionsRequired[0]) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(BaseMapActivity.this, permissionsRequired[1]) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(BaseMapActivity.this, permissionsRequired[0]) || ActivityCompat.shouldShowRequestPermissionRationale(BaseMapActivity.this, permissionsRequired[1])) {
boolean foreground = ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
boolean background = ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED;
if (foreground || background) {
proceedAfterPermission();
} else {
androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(BaseMapActivity.this);
builder.setTitle("Need App Location Permission");
builder.setMessage("App name need location permission to show your current location.");
builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
ActivityCompat.requestPermissions(BaseMapActivity.this, permissionsRequired, PERMISSION_CALLBACK_CONSTANT);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
builder.show();
}
} else if (permissionStatus.getBoolean(permissionsRequired[0], false) && permissionStatus.getBoolean(permissionsRequired[1], false)) {
boolean foreground = ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
boolean background = ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED;
if (foreground || background) {
proceedAfterPermission();
} else {
androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(BaseMapActivity.this);
builder.setTitle("GPS Not Enabled");
builder.setMessage("Enable GPS from your setting");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
sentToSettings = false;
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
} else {
ActivityCompat.requestPermissions(BaseMapActivity.this, permissionsRequired, PERMISSION_CALLBACK_CONSTANT);
}
SharedPreferences.Editor editor = permissionStatus.edit();
editor.putBoolean(permissionsRequired[0], true);
editor.commit();
} else {
proceedAfterPermission();
}
}
IV)
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (requestCode == PERMISSION_CALLBACK_CONSTANT) {
boolean allgranted = false;
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
allgranted = true;
} else {
allgranted = false;
break;
}
}
if (allgranted) {
proceedAfterPermission();
} else if (ActivityCompat.shouldShowRequestPermissionRationale(BaseMapActivity.this, permissionsRequired[0])
|| ActivityCompat.shouldShowRequestPermissionRationale(BaseMapActivity.this, permissionsRequired[1])
) {
boolean foreground = ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
boolean background = ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED;
if (foreground || background) {
proceedAfterPermission();
} else {
androidx.appcompat.app.AlertDialog.Builder builder = new AlertDialog.Builder(BaseMapActivity.this);
builder.setTitle("Need App Location Permission");
builder.setMessage("App name need location permission to show your current location");
builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
ActivityCompat.requestPermissions(BaseMapActivity.this, permissionsRequired, PERMISSION_CALLBACK_CONSTANT);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
finish();
}
});
builder.show();
}
} else {
proceedAfterPermission();
}
}
}
V)
private void proceedAfterPermission() {
//Do your stuff after permission
}

How to detect if user disable granted permissions in the settings in android?

In android 6.0 and above the permissions granted at run time and the user can cancel the granted permissions by going to the settings.
I want to run some code just after the user cancels the granted permissions by going to the settings. Is there anyway to do it?
// call this for checking the permission before other Activity or function //to call
if (hasPermission()) {
// do thing
} else {
requestPermissionDialog();
}
/////////////////hasPermission////////////////////////////
private boolean hasPermission() {
boolean permission = true;
if (ActivityCompat.checkSelfPermission(WelcomeActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
permission = false;
}
return permission;
}
//////////////////////////requestPermissionDialog///////////////////////
private void requestPermissionDialog() {
permissionStatus = getSharedPreferences("permissionStatus", MODE_PRIVATE);
if (ActivityCompat.checkSelfPermission(WelcomeActivity.this, Manifest.permission.WRITE_Eenter code hereXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(WelcomeActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//Show Information about why you need the permission
// resetPasswordDialog(WelcomeActivity.this,"ok");
AlertDialog.Builder builder = new AlertDialog.Builder(WelcomeActivity.this);
builder.setInverseBackgroundForced(true);
builder.setTitle("Storage Permission");
builder.setMessage("This app needs Storage permission.");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
ActivityCompat.requestPermissions(WelcomeActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_CONSTANT);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
} else if (permissionStatus.getBoolean(Manifest.permission.WRITE_EXTERNAL_STORAGE, false)) {
//Previously Permission Request was cancelled with 'Dont Ask Again',
// Redirect to Settings after showing Information about why you need the permission
// resetPasswordDialog(WelcomeActivity.this,"settings");
AlertDialog.Builder builder = new AlertDialog.Builder(WelcomeActivity.this);
builder.setInverseBackgroundForced(true);
builder.setTitle(" Storage Permission");
builder.setMessage("This app needs Storage permission.");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
sentToSettings = true;
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
Toast.makeText(getBaseContext(), "Go to Permissions to allow Storage Audio ", Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
} else {
//just request the permission
ActivityCompat.requestPermissions(WelcomeActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_CONSTANT);
}
SharedPreferences.Editor editor = permissionStatus.edit();
editor.putBoolean(Manifest.permission.WRITE_EXTERNAL_STORAGE, true);
editor.commit();
}
}

Android request location permission causes alertdialog to display twice

I am trying to display user current location when clicking a button using this code:
mButton = (Button) findViewById(R.id.mButton);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String[] permissions;
permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(MainActivity.this, permissions, 4);
else {
mButton.setText("");
// request and display location
}
}
});
So far, so good, but when I am checking the permissions results (onRequestPermissionsResult) I am using a for statement to iterate the permissions array and inside I am creating a dialog to explain why the current permission is needed. The problem is - because the permissions needed are ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION the for statement runs twice, here is my code:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if (requestCode == 4) {
for (int i = 0, len = permissions.length; i < len; i++) {
String permission = permissions[i];
if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
boolean showRationale = shouldShowRequestPermissionRationale(permission);
if (!showRationale) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("The application must have permission to find location");
builder.setTitle("Location");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", MainActivity.this.getPackageName(), null);
intent.setData(uri);
MainActivity.this.startActivity(intent);
}
});
builder.setNegativeButton("Later", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
} else if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permission) || Manifest.permission.ACCESS_FINE_LOCATION.equals(permission)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("The application must have permission to find location");
builder.setTitle("Location");
builder.setNegativeButton("Later", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String[] permissionss = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
ActivityCompat.requestPermissions(MainActivity.this, permissionss, 4);
}
});
builder.show();
}
Toast.makeText(MainActivity.this, "No permission to use location", Toast.LENGTH_LONG).show();
} else if (grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED)
// request and display location
}
}
}
}
There are many solutions I thought of, passing only one permission in the permissions String[] array, showing the dialog with an if statement only if(i==0). I don't know what is the correct solution for this problem. Thanks.
P.S - Sorry for my English.
NEW FINAL WORKING CODE WITH LIBRARY:
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
requestLocation();
else
MainActivityPermissionsDispatcher.requestLocationWithCheck(MainActivity.this);
}
});
#NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
public void requestLocation() {
double lo = 0.0, la = 0.0;
removeItem();
myToast = Toast.makeText(MainActivity.this, lo + " , " + la, Toast.LENGTH_LONG);
myToast.show();
// Get Location And Display It Using Toast.
showQuestion("Location");
}
#OnNeverAskAgain({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
void showNeverAskForLocation() {
Toast.makeText(this, R.string.permission_location_neverask, Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("The application must have permission to find location");
builder.setTitle("Location");
builder.setPositiveButton(R.string.button_allow, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", MainActivity.this.getPackageName(), null);
intent.setData(uri);
MainActivity.this.startActivity(intent);
}
});
builder.setNegativeButton(R.string.button_deny, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
#OnShowRationale({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
void showRationaleForLocation(final PermissionRequest request) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("The application must have permission to find location");
builder.setTitle("Location");
builder.setPositiveButton(R.string.button_allow, new DialogInterface.OnClickListener() {
#Override
public void onClick(#NonNull DialogInterface dialog, int which) {
request.proceed();
}
});
builder.setNegativeButton(R.string.button_deny, new DialogInterface.OnClickListener() {
#Override
public void onClick(#NonNull DialogInterface dialog, int which) {
request.cancel();
}
});
builder.show();
}
#OnPermissionDenied({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
void showDeniedForLocation() {
Toast.makeText(this, R.string.permission_location_denied, Toast.LENGTH_SHORT).show();
}

Categories

Resources