on my app i have implemented a splash activity that check if is first run app and if is true show a dialog message, this is the code:
public void onConnected(Bundle connectionHint) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
myLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
}
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean isFirstStart = getPrefs.getBoolean("firstStart", true);
if (isFirstStart) {
android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(splashscreen.this).create();
alertDialog.setTitle(getResources().getString(R.string.titolo_intro_sms));
alertDialog.setMessage(getResources().getString(R.string.intro_sms));
alertDialog.setButton(android.app.AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(splashscreen.this, MainActivity.class);
startActivity(i);
}
});
alertDialog.show();
SharedPreferences.Editor e = getPrefs.edit();
e.putBoolean("firstStart", false);
e.apply();
} else {
startApp();
}
}
When dialog are show if click ok i open MainActivity. Now after 'Ok' click into dialog befor to start MainActivity i would like to show a dialog request permission.
I have create a abstract class for this and i call in this way:
requestAppPermissions(new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION},
R.string.msg,REQUEST_PERMISSION);
Now i set this line code into OnCreate the permission request are show before the splash activity but if i set into onClick methos of 'ok' allert dialog is not show.
How i can show the permission request after click ok befor to start Main Activity?
Any help is great
Thanks
I have integrate my onRequestPermissionresult into abstract class in this way:
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
int permissionCheck = PackageManager.PERMISSION_GRANTED;
for(int permisson : grantResults) {
permissionCheck = permissionCheck + permisson;
}
if( (grantResults.length > 0) && PackageManager.PERMISSION_GRANTED == permissionCheck) {
onPermissionsGranted(requestCode);
Intent i = new Intent(this, MainActivity.class); //start activity
startActivity(i);
} else {
//Display message when contain some Dangerous permisson not accept
Snackbar.make(findViewById(android.R.id.content), mErrorString.get(requestCode),
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE", new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.setData(Uri.parse("package:" + getPackageName()));
i.addCategory(Intent.CATEGORY_DEFAULT);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(i);
}
}).show();
}
}
and the message permission are show after ok click but after the app close and not open MainActivity
i have change my splashcrenn and i have set all method about permsion into it, this is code:
public void onPermissionsGranted(int requestCode) {
}
public void requestAppPermissions(final String[]requestedPermissions, final int stringId, final int requestCode) {
mErrorString.put(requestCode, stringId);
int permissionCheck = PackageManager.PERMISSION_GRANTED;
boolean showRequestPermissions = false;
for(String permission: requestedPermissions) {
permissionCheck = permissionCheck + ContextCompat.checkSelfPermission(this, permission);
showRequestPermissions = showRequestPermissions || ActivityCompat.shouldShowRequestPermissionRationale(this, permission);
}
if (permissionCheck!=PackageManager.PERMISSION_GRANTED) {
if(showRequestPermissions) {
Snackbar.make(findViewById(android.R.id.content), stringId, Snackbar.LENGTH_INDEFINITE).setAction("GRANT", new View.OnClickListener() {
#Override
public void onClick(View v) {
ActivityCompat.requestPermissions(splashscreen.this, requestedPermissions, requestCode);
}
}).show();
} else {
ActivityCompat.requestPermissions(this, requestedPermissions, requestCode);
}
} else {
onPermissionsGranted(requestCode);
}
}
#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();
Intent i = new Intent(splashscreen.this, MainActivity.class); //start activity
splashscreen.this.startActivity(i);
} else {
Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
into dialog 'ok' click button i have set this:
alertDialog.setButton(android.app.AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(splashscreen.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
/*Intent i = new Intent(splashscreen.this, MainActivity.class);
startActivity(i);*/
}
});
alertDialog.show();
but when i click ok the app close and not open MainActivity
try this:
show permission dialog in button click:
alertDialog.setButton(android.app.AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1); //show reuest dialog
}
});
alertDialog.show();
Now catch the result in onRequestPermissionsResult() and start your MainActivity
#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(getContext(), "Permission granted", Toast.LENGTH_SHORT).show();
Intent i = new Intent(splashscreen.this, MainActivity.class); //start activity
startActivity(i);
} else {
Toast.makeText(getContext(), "Permission denied", Toast.LENGTH_SHORT).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
in your abstract class pass your activity context and use it to start MainActivity
To pass context:
class YourAbstractClass{
// variable to hold context
private Context context;
//save the context recievied via constructor in a local variable
public YourAbstractClass(Context context){ //constructor
this.context=context;
}
}
In your splash Activity call your Abstract class like:
YourAbstractClass class = new YourAbstractClass(this); //pass context
Now use the context to startActivity
Intent myIntent = new Intent(context, MainActivity.class);
context.startActivity(myIntent);
Request the permission after you click ok, but don't start the activity right away. Wait for the result in onRequestPermissionResult, and start your MainActivity there.
Use if-else statement in your button call.
If you already have permission then execute the MainActivity call in
if part. If not then ask for permission in else part of if-else.
Now use OnRequestPermissionResult method to which is called when permissions are granted or denied. If permissions are granted in this method then again execute the MainActivity call or else just do what you need to do when permission denied like show him the reason why you need permission and try again or just exit.
Hope it helped. For everything about permissions in android in a simplified version just click HERE (http://www.vogella.com/tutorials/AndroidPermissions/article.html).
Related
This issue happens when I deliberately don't do anything when the permission request screen pops up, the app will just crash after a few seconds.
The permission requests pop up after transitioned from another activity (LoginActivity) to MapsActivity.
LoginActivity
if statement to check the validity
if valid
Intent intent = new Intent(LoginActivity.this,MapActivity.class);
startActivity(intent);
finish();
MapActivity
...
public void onMapReady(GoogleMap map) {
mMap = map;
getLocationPermission();
updateLocationUI();
getDeviceLocation();
}
private void getLocationPermission() {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
}
Just realised how to solve this with a simpled solution lmao...
In my original code, I have onRequestPermissionResult() already btw.
MapActivity
private boolean mLocationPermissionGranted;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
mLocationPermissionGranted = false;
switch (requestCode) {
case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
}
}
}
updateLocationUI();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
...
getLocationPermission();
if(mLocationPermissionGranted){
updateLocationUI();
getDeviceLocation();
}
}
No more crashing now :)
i am checking the permission this way and this is working properly try this :-
if (checkLocationPermission()) {
Log.e("Tag", "Camera and External storage Permission's are allowed");
} else {
requestLocationPermission();
}
this is the method checkLocationPermission:-
private boolean checkLocationPermission() {
int result = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
this is request method for location:-
private void requestLocationPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale
(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this, R.style.DialogTheme);
alertDialog.setMessage("You Have To Give Permission From Your Device Setting To go in Setting Please Click on Settings Button");
alertDialog.setCancelable(false);
alertDialog.setPositiveButton("Go To Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
});
alertDialog.show();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1012);
}
}
and finally onRequestPermissionsResult:-
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this, R.style.DialogTheme);
alertDialog.setMessage("You Have To Give Permission From Your Device Setting To go in Setting Please Click on Settings Button");
alertDialog.setCancelable(false);
alertDialog.setPositiveButton("Go To Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
});
alertDialog.show();
}else{
// do your stuff in case accept permission
}
}
I'm working on checking and getting permission from user with API level 23 and above. So here is a confusing thing for me, android.com says:
shouldShowRequestPermissionRationale() method returns true if the app has requested this permission previously and the user denied the request.
If the user turned down the permission request in the past and chose the Don't ask again option in the permission request system dialog, this method returns false
in other side it gives following code for checking permission and request permission if its neccessery
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// 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.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
else scope in above example runs if user doesn't allow permission and check Don't Ask Again, Right? So with this code user never being asked for permission at first time run. I tested that code and the result is what I expected.
So How could I request permission for first time run and do something if user previously denied my request and do something if user deny my request and check Don't Ask Again?
You can do the following.
Ask permission every time by only checking that permission is not granted already. Don't handle the "Don't ask again" in this method. (if user checks "Don't ask again" the OS will automatically handle and will not ask for permission again and will give a call back of permission denied)
Handle the ActivityCompat.shouldShowRequestPermissionRationale() in the call back method onRequestPermissionsResult().
Here is my code in which I am asking for permission everytime
public void checkAndAskCameraPermission() {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(context,
new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST_ID);
}
}
This is how I handles the call back
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case CAMERA_PERMISSION_REQUEST_ID: {
if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
// Do something if permission is not granted and the user has also checked the **"Don't ask again"**
} else if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_DENIED) {
// Do something if permission not granted
}
}
}
}
first check if the permission is granted then do what you need
else if permission is denied then check weather you should request the permission you need or not through shouldShowRequestPermissionRationale.
if shouldShowRequestPermissionRationale return false then you can just show a message to the user to told them to enable the permission manually.
other then if shouldShowRequestPermissionRationale return true then request the permission and get the result of granting permission in onRequestPermissionsResult
update , this is just a simple code to show the steps:
if (checkSelfPermission == granted){
// do what you want
} else if (shouldShowRequestPermissionRationale == true) {
// you can request the permission you want from the user, then check whether permission granted or not inside onRequestPermissionsResult method
} else {
// here you know the permission is not granted , and also the user check on "Dont ask Again!" checkbox, so all you can to do is just tell the user to enable the permission manually from app permissions through Toast message or any thing else
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//initilize your views
if(iscontactsAllowed){
// do your code here
} else {
requestcontactsPermission();
}
}
private void requestcontactsPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_CONTACTS)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
Log.d("scancode", "denied permission before");
}
Log.d("perm", "fourth");
//And finally ask for the permission
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_CONTACTS}, READ_CONTACTS_CODE /*can be any interge */);
}
private boolean iscontactsAllowed() {
//Getting the permission status
int result = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_CONTACTS);
//If permission is granted returning true
if (result == PackageManager.PERMISSION_GRANTED)
return true;
//If permission is not granted returning false
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if(requestCode == READ_CONTACTS_CODE){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// you have the permission call yur method here
} else {
// permission denied show user why you need it or ask again by calling reuestpermission if you need the permission
}
}
#ArtinArtin I have expanded on #salmanyahya updated simple code and provided my logic with Alert Dialog's and one Snackbar (not a big fan of Snackbar's) any way see if this helps
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
//.... write file into storage ...
System.out.println("SDK > BuildVersion TRUE");
} else {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 666); // Comment 26
System.out.println("go to requestPermissions");
}
}
onLoad();
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 666: // Allowed was selected so Permission granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Snackbar s = Snackbar.make(findViewById(android.R.id.content),"Permission Granted",Snackbar.LENGTH_LONG);
View snackbarView = s.getView();
TextView textView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.RED);
textView.setTextSize(18);
textView.setMaxLines(6);
s.show();
// do your work here
} else if (Build.VERSION.SDK_INT >= 23 && !shouldShowRequestPermissionRationale(permissions[0])) {
// User selected the Never Ask Again Option Change settings in app settings manually
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Change Permissions in Settings");
alertDialogBuilder
.setMessage("" +
"\nClick SETTINGS to Manually Set\n"+"Permissions to use Database Storage")
.setCancelable(false)
.setPositiveButton("SETTINGS", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, 1000); // Comment 3.
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
} else {
// User selected Deny Dialog to EXIT App ==> OR <== RETRY to have a second chance to Allow Permissions
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Second Chance");
alertDialogBuilder
.setMessage("Click RETRY to Set Permissions to Allow\n\n"+"Click EXIT to the Close App")
.setCancelable(false)
.setPositiveButton("RETRY", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Integer.parseInt(WRITE_EXTERNAL_STORAGE));
Intent i = new Intent(MainActivity.this,MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
})
.setNegativeButton("EXIT", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
break;
}};
This code helps to handles the run time permission Management in Android
public String storagePermissions = Manifest.permission.READ_EXTERNAL_STORAGE;
private static final int REQUEST_ACCESS =101;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(checkSelfPermission(storagePermissions)== PackageManager.PERMISSION_GRANTED){
result(); // result is your block of code
}else {
requestPermissions(new String[]{storagePermissions},REQUEST_ACCESS);
}
}
else{
result(); //so if user is lower than api verison M, no permission is requested
}
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setTitle("Hi User..")
.setPositiveButton("Ok", okListener)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) { //idea calling showMessage funtion again
Snackbar mySnackbar = Snackbar.make( findViewById(R.id.coordinatorlayout),"You Press Cancel.. ", Snackbar.LENGTH_INDEFINITE);
mySnackbar.setAction("Exit", new cancelButton());
mySnackbar.show();
}
})
.create()
.show();
}
private void result(){
//your code
}
#RequiresApi(api = Build.VERSION_CODES.M)
public class NeverAskAgain implements View.OnClickListener{
#Override
public void onClick(View view)
{
goToSettings();
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void goToSettings() {
Intent myAppSettings = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + getPackageName()));
finish();
myAppSettings.addCategory(Intent.CATEGORY_DEFAULT);
myAppSettings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(myAppSettings, REQUEST_APP_SETTINGS);
}
public class cancelButton implements View.OnClickListener{
#Override
public void onClick(View view){
Toast.makeText(MainActivity.this,"To use this app , you must grant storage permission",Toast.LENGTH_SHORT);
finish();
}
}
#Override
#RequiresApi(api = Build.VERSION_CODES.M)
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode,permissions,grantResults);
switch(requestCode) {
case REQUEST_ACCESS:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission is granted
result();
break;
}
else if (!shouldShowRequestPermissionRationale(permissions[0])){
showMessageOKCancel("You choose Never Ask Again,option",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Snackbar mySnackbar = Snackbar.make(findViewById(R.id.coordinatorlayout), "Permission=>Storage=>On", Snackbar.LENGTH_INDEFINITE);
mySnackbar.setAction("Settings", new NeverAskAgain());
mySnackbar.show();
}
});
break;
}
else {
showMessageOKCancel("You Denid permission Request..",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions(new String[]{storagePermissions}, REQUEST_ACCESS);
}
});
break;
}
}
}
What I have found is that shouldShowRequestPermissionRationale only returns true if the user has denied permission (at least once) and not selected "Don't Ask Again". Meaning, it won't be displayed on the first time the permission is requested either.
I want to re ask the permission to the user in the situation if he/she deny for the first time. I have set the permission but my app runs even if I press deny option. I have a code which should do the things which I want to do but I get Cant resolve symbol Snackbar when I hit Alt+Enter it created another activity and remaining -make and -permision_available_camera gets red error.
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA) {
// BEGIN_INCLUDE(permission_result)
// Received permission result for camera permission.
Log.i(TAG, "Received response for Camera permission request.");
// Check if the only required permission has been granted
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Camera permission has been granted, preview can be displayed
Log.i(TAG, "CAMERA permission has now been granted. Showing preview.");
Snackbar.make(mLayout, R.string.permision_available_camera,
Snackbar.LENGTH_SHORT).show();
} else {
Log.i(TAG, "CAMERA permission was NOT granted.");
Snackbar.make(mLayout, R.string.permissions_not_granted,
Snackbar.LENGTH_SHORT).show();
}
#Arjun Thakun Here is a way to manage the concept of ask permission again and deal with all the ways the user can answer when the app asks about permissions
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
//.... write file into storage ...
System.out.println("SDK > BuildVersion TRUE");
} else {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 666); // Comment 26
System.out.println("go to requestPermissions");
}
}
onLoad();
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 666: // Allowed was selected so Permission granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Snackbar s = Snackbar.make(findViewById(android.R.id.content),"Permission Granted",Snackbar.LENGTH_LONG);
View snackbarView = s.getView();
TextView textView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.RED);
textView.setTextSize(18);
textView.setMaxLines(6);
s.show();
// do your work here
} else if (Build.VERSION.SDK_INT >= 23 && !shouldShowRequestPermissionRationale(permissions[0])) {
// User selected the Never Ask Again Option Change settings in app settings manually
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Change Permissions in Settings");
alertDialogBuilder
.setMessage("" +
"\nClick SETTINGS to Manually Set\n"+"Permissions to use Database Storage")
.setCancelable(false)
.setPositiveButton("SETTINGS", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, 1000); // Comment 3.
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
} else {
// User selected Deny Dialog to EXIT App ==> OR <== RETRY to have a second chance to Allow Permissions
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Second Chance");
alertDialogBuilder
.setMessage("Click RETRY to Set Permissions to Allow\n\n"+"Click EXIT to the Close App")
.setCancelable(false)
.setPositiveButton("RETRY", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Integer.parseInt(WRITE_EXTERNAL_STORAGE));
Intent i = new Intent(MainActivity.this,MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
})
.setNegativeButton("EXIT", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
break;
}};
Try this
Basically here we are trying to read the content from the External Storage. For that, we have to ask the user for runtime permission. If the user allows it's fine, but if the user denies the permission it will display a second dialog/message box until the user accepts the permission
Asking for permission
If the user denies it will display the 'Permission Needed' dialog whenever the user launches the application
If the user presses the OK button it will ask permission again.
public class MainActivity extends AppCompatActivity {
public static int REQUEST_PERMISSION=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
permission_fn();
}
private void requestStoragePermission()
{
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE))
{
new AlertDialog.Builder(this)
.setTitle("Permission Needed")
.setMessage("Permission is needed to access files from your device...")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},REQUEST_PERMISSION);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
}
else
{
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},REQUEST_PERMISSION);
}
}
private void permission_fn()
{
if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.READ_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED)
{
if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE))
{
}
else
{
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},REQUEST_PERMISSION);
}
}
else {
requestStoragePermission();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Thanks for enabling the permission", Toast.LENGTH_SHORT).show();
//do something permission is allowed here....
} else {
Toast.makeText(this, "Please allow the Permission", Toast.LENGTH_SHORT).show();
}
}
}
}
Add user permission in AndroidManifest.xml file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
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.
}
});
I know this question has been asked number of times but none of the methods are working for me. I have a v4.nested fragment and I am calling requestPermission but I don't even get the dialog to show and hence onRequestPermissionsResult is not getting called. I have tried call the onRequestPermissionsResult in both my Activity and Fragment but nothing is working. I am using appcompat-v7:23.3.0 so I was expecting the dialog and hence the result. Any help? Thanks
Code
public void ask(){
Log.e("Here", "Permission");
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_GRANTED) {
Log.e("Here", "Granted");
if (what == 1){
PackageManager pm = getActivity().getPackageManager();
if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
getActivity().startActivityForResult(i, CAMERA_PIC_REQUEST);
} else {
Toast.makeText(getActivity(), "Can't detect Camera on device", Toast.LENGTH_LONG).show();
}
}
else{
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
getActivity().startActivityForResult(i, RESULT_LOAD_IMAGE);
}
}
else{
Log.e("Here", "Ask");
if (useRuntimePermissions()) {
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
showMessageOKCancel("You need to allow access to Device Storage",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions(new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 3);
Log.e("A", "ash");
}
});
} else {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},2);
Log.e("B", "Should be Asked by now");
}
}
}
}
private boolean useRuntimePermissions() {
return(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new android.support.v7.app.AlertDialog.Builder(getActivity())
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
#Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
Log.e("Hehe", "results"+String.valueOf(requestCode));
switch (requestCode) {
case CAM_REQUEST: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (what == 1){
PackageManager pm = getActivity().getPackageManager();
if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
getActivity().startActivityForResult(i, CAMERA_PIC_REQUEST);
} else {
Toast.makeText(getActivity(), "Can't detect Camera on device", Toast.LENGTH_LONG).show();
}
}
else{
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
getActivity().startActivityForResult(i, RESULT_LOAD_IMAGE);
}
}
else {
Toast.makeText(getActivity(), "Camera Request not granted. Please enable it at App Settings", Toast.LENGTH_LONG).show();
}
return;
}
}
}
The ask() method is called from a button tap onsetClickListener and LogA and LogB are logging but the permission dialog doesn't show.