Android request location permission causes alertdialog to display twice - android

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();
}

Related

Android Background Location Permissions

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);
}
}

Get Location Permission from User in Android App

I am implementing Access Location from user.Following is my Code. My problem is When I am clicking on Location permission it not getting the location.Bt when i am manually turn on the location from setting after that it giving me the location.My requirement is i Want compulsory check the Location permission from my App i.e. (it goes to setting and turn on location) .I gave all Permission in AndroidMeanifest file.And following is my SpashScreen.
package com.example.sbaapp;
public class SpashScreen extends AppCompatActivity {
AlertDialog.Builder alertDialog;
String[] perms = {"android.permission.ACCESS_FINE_LOCATION", "android.permission.READ_SMS"};
int permsRequestCode = 200;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spash_screen);
alertDialog = new AlertDialog.Builder(SpashScreen.this, R.style.Theme_AppCompat_DayNight_DarkActionBar);
FirebaseApp.initializeApp(getApplicationContext());
//requestPermissions(perms, permsRequestCode);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(!CheckPermissions()){
requestPermissions(perms,permsRequestCode);
}
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
private boolean CheckPermissions() {
int LocationPermission=checkSelfPermission(perms[0]);
int ReadSmsPermission=checkSelfPermission(perms[1]);
Log.d("Inside Permission","");
return LocationPermission== PackageManager.PERMISSION_GRANTED && ReadSmsPermission==PackageManager.PERMISSION_GRANTED;
}
#Override
protected void onStart() {
super.onStart();
SubscribeToTopic();
if (new SessionManager(getApplicationContext()).ISLOGIN()) {
Intent intent = new Intent(SpashScreen.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SpashScreen.this, Activity_home.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}, 60000);
}
}
private void SubscribeToTopic() {
FirebaseMessaging.getInstance().subscribeToTopic("SBASURVEY")
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
String msg = "SuccessGeneralNot";
if (!task.isSuccessful()) {
msg = "Failed";
}
Log.d("TopicstatusForGeneral", msg);
}
});
}
#Override
public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults){
switch(permsRequestCode){
case 200:
boolean locationAccepted = false;
boolean smspermissionaccepted=false;
if(grantResults.length>=2) {
locationAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
smspermissionaccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
}else if(grantResults.length>=1){
if(permissions[0].equals("android.permission.ACCESS_FINE_LOCATION")){
locationAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
smspermissionaccepted=true;
}else {
locationAccepted=true;
smspermissionaccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
}
}
if(!(locationAccepted || smspermissionaccepted)){
new AlertDialog.Builder(SpashScreen.this).setMessage("You Need Accept Both the permissions In Order to Smooth Working Of Application Functionality")
.setPositiveButton("Ok",new SpashScreen.OkListenerForBoth())
.setNegativeButton("Cancel",null)
.create()
.show();
}else if(!locationAccepted){
new AlertDialog.Builder(SpashScreen.this).setMessage("You Need Accept This Location Based permissions In Order to Smooth Working Of Application Functionality")
.setPositiveButton("Ok",new SpashScreen.OkListenerForLocation())
.setNegativeButton("Cancel",null)
.create()
.show();
}
else if(!smspermissionaccepted){
new AlertDialog.Builder(SpashScreen.this).setMessage("You Need Accept This SMS Read permissions In Order to Smooth Working Of Application Functionality")
.setPositiveButton("Ok",new SpashScreen.OkListenerForSmS())
.setNegativeButton("Cancel",null)
.create()
.show();
}
break;
}
}
public class OkListenerForBoth implements AlertDialog.OnClickListener{
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions(perms,permsRequestCode);
}
}
public class OkListenerForLocation implements AlertDialog.OnClickListener{
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions(new String[]{perms[0]},permsRequestCode);
}
}
public class OkListenerForSmS implements AlertDialog.OnClickListener{
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions(new String[]{perms[1]},permsRequestCode);
}
}
}
Use the code below it will open a location request dialog and then you will be able to get the location.
if (googleApiClient == null) {
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);
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:
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(
getActivity(), 1000);
} catch (IntentSender.SendIntentException e) {
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
}
Please do this way
add library in app from gradle
// Dexter runtime permissions
implementation 'com.karumi:dexter:5.0.0'
// add permissions in manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
// please call this method in your oncreate() method of splash.
requestPermission();
/**
* Requesting multiple permissions (storage and location) at once
* This uses multiple permission model from dexter
* On permanent denial opens settings dialog
*/
private void requestPermission() {
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
Log.e(TAG, "All permissions are granted!");
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// show alert dialog navigating to Settings
showSettingsDialog();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).
withErrorListener(new PermissionRequestErrorListener() {
#Override
public void onError(DexterError error) {
Toast.makeText(getApplicationContext(), "Error occurred! ", Toast.LENGTH_SHORT).show();
}
})
.onSameThread()
.check();
}
/**
* Showing Alert Dialog with Settings option
* Navigates user to app settings
* NOTE: Keep proper title and message depending on your app
*/
private void showSettingsDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Need Permissions");
builder.setMessage("This app needs permission to use this feature. You can grant them in app settings.");
builder.setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
openSettings();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
// navigating user to app settings
private void openSettings() {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, 101);
}
Hope it will help

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 call runtime permission with dialog

I have app that requests runtime permission for call on app start with dialog, but somehow my code doesn't request any permission or work. I need that when the app starts; ask the user for permission to call and in case the user refused, ask again for permission and move to in permissions settings.
Here's my code:
public class MainActivity extends AppCompatActivity {
private FirebaseAnalytics mFirebaseAnalytics;
private AdView mAdView;
private Button button_id;
private Button button_mobily;
private Button button_stc;
private Button button_zain;
private Button button_share;
private Button button_exit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dash);
NativeExpressAdView adView = (NativeExpressAdView)findViewById(R.id.adView);
AdRequest request = new AdRequest.Builder().build();
adView.loadAd(request);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "main");
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "opened");
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "image");
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
isPermissionGranted();
button_exit = (Button) findViewById(R.id.exit_buton_id);
button_share = (Button) findViewById(R.id.Share_buton);
button_id = (Button) findViewById(R.id.edit_id);
button_mobily = (Button) findViewById(R.id.mobily_buton);
button_stc = (Button) findViewById(R.id.stc_buton);
button_zain = (Button) findViewById(R.id.zain_buton);
button_id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent myIntent = new Intent(MainActivity.this, NationalId.class);
MainActivity.this.startActivity(myIntent);
}
});
button_share.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
try {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "test");
String sAux = "\n download my app\n\n";
sAux = sAux + "https://play.google.com/store/apps/details?id=Orion.Soft \n\n";
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, "share on"));
} catch (Exception e) {
//e.toString();
}
}
});
button_exit.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
close();
}
});
button_mobily.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(MainActivity.this, OpreatorMobily.class);
MainActivity.this.startActivity(myIntent);
}
});
button_stc.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(MainActivity.this, OpreatorSTC.class);
MainActivity.this.startActivity(myIntent);
}
});
button_zain.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(MainActivity.this, OpreatorZain.class);
MainActivity.this.startActivity(myIntent);
}
});
}
public boolean isPermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.CALL_PHONE)
== PackageManager.PERMISSION_GRANTED) {
Log.v("TAG", "Permission is granted");
return true;
} else {
Log.v("TAG", "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, 1);
return false;
}
} else { //permission is automatically granted on sdk<23 upon installation
Log.v("TAG", "Permission is granted");
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
public void close() {
// TODO Auto-generated method stub
finish();
System.exit(0);
}
}
You don't need to check the Android version, Android is smart enough to know what the OS version is on the user's device.
Also if you're trying to get the ability to Call you need to change how the permission is called.
public boolean isPermissionGranted() {
Intent callOfficeIntent = new Intent(Intent.ACTION_CALL);
callOfficeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
callOfficeIntent.setData(Uri.parse("tel:" + mNumberToCall));
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CALL_PHONE},
10);
return;
} else {
try {
startActivity(callOfficeIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "No number to call", Toast.LENGTH_SHORT).show();
}
}
}
If you just want to get the permission but not make the call right away place this inside your method. This just asks for permission as a DialogBox.
if(ActivityCompat.checkSelfPermission(getActivity(),Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),Manifest.permission.READ_PHONE_STATE)){
//Show Information about why you need the permission
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Need Permission");
builder.setMessage("This app needs phone permission.");
builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE},PERMISSION_CALLBACK_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.READ_PHONE_STATE,false)) {
//Previously Permission Request was cancelled with 'Dont Ask Again',
// Redirect to Settings after showing Information about why you need the permission
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Need Permission");
builder.setMessage("This app needs storage permission.");
builder.setPositiveButton("Grant", 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", getActivity().getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
Toast.makeText(getActivity(), "Go to Permissions to Grant Phone", 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
requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE},PERMISSION_CALLBACK_CONSTANT);
}
txtPermissions.setText("Permissions Required");
SharedPreferences.Editor editor = permissionStatus.edit();
editor.putBoolean(Manifest.permission.READ_PHONE_STATE,true);
editor.commit();
} else {
//You already have the permission, just go ahead.
proceedAfterPermission();
}
}
});
}
private void proceedAfterPermission() {
txtPermissions.setText("We've got the permission");
Toast.makeText(getActivity(), "We got All Permissions", Toast.LENGTH_LONG).show();
}
Don't have to use the last method, just change the textView to a toast.
I found a simple Github library developed by "Nabin Bhandari". It is easy to implement and can be customized directly. Github library link...
Please add this dependency to add this library to your code.
implementation 'com.nabinbhandari.android:permissions:3.8'
This allow you to request single permission, multiple permission and do customize your own dialog.
Furthermore,
You can also override other methods like onDenied, onJustBlocked, etc if you want to change the default behaviour.
Dialogue messages and texts can be modified by building the options parameter.
See documentation in the source code for more customizations.
Use this code to ask multiple permissions samuntanely.
String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
Permissions.check(this/*context*/, permissions, null/*rationale*/, null/*options*/, new PermissionHandler() {
#Override
public void onGranted() {
// do your task.
}
});
Use this code if you want to Customized permissions request:
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
String rationale = "Please provide location permission so that you can ...";
Permissions.Options options = new Permissions.Options()
.setRationaleDialogTitle("Info")
.setSettingsDialogTitle("Warning");
Permissions.check(this/*context*/, permissions, rationale, options, new PermissionHandler() {
#Override
public void onGranted() {
// do your task.
}
#Override
public void onDenied(Context context, ArrayList<String> deniedPermissions) {
// permission denied, block the feature.
}
});

Categories

Resources