requestPermission not showing in support Fragment - android

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.

Related

How to upload Image in Android Studio

this is my .java class
package com.example.gas4u;
private void showImagePickDialog() {
//options to display in dialog
String[] options = {"Camera","Gallery"};
//dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick Image")
.setItems(options, new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which){
//handle items clicks
if (which == 0){
//camera clicked
if (checkCameraPermission()){
//permission granted
pickFromCamera();
}
else{
//permission not granted, request
requestCameraPermission();
}
}
else{
//gallery clicked
if (checkStoragePermission()){
//permission granted
pickFromGallery();
}
else{
//permission not granted
requestStoragePermission();
}
}
}
}).show();
}
// You can do the assignment inside onAttach or onCreate, i.e, before the activity is displayed
ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result ) {
if (result.getResultCode() == Activity.RESULT_OK) {
// There are no request codes
Intent data = result.getData();
if (result.getResultCode() == IMAGE_PICK_GALLERY_CODE){
//image picked from gallery
//save picked image uri
image_uri = data.getData();
//set image
productIconIv.setImageURI(image_uri);
}
else if (result.getResultCode() == IMAGE_PICK_CAMERA_CODE){
//image picked from camera
productIconIv.setImageURI(image_uri);
}
}
}
});
private void pickFromGallery(){
//intent to pick image from gallery
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
someActivityResultLauncher.launch(intent);
//(intent, IMAGE_PICK_GALLERY_CODE);
}
private void pickFromCamera(){
//intent to pick image from camera
//using media store to pick high/original quality image
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.TITLE, "Temp_Image_Title");
contentValues.put(MediaStore.Images.Media.DESCRIPTION, "Temp_Image_Description");
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
Intent intent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
someActivityResultLauncher.launch(intent);
//startActivityForResult(intent, IMAGE_PICK_CAMERA_CODE);
}
private boolean checkStoragePermission(){
boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
(PackageManager.PERMISSION_GRANTED);
return result; //returns true or false
}
private void requestStoragePermission(){
ActivityCompat.requestPermissions(this, storagePermission, STORAGE_REQUEST_CODE);
}
private boolean checkCameraPermission(){
boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) ==
(PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
(PackageManager.PERMISSION_GRANTED);
return result && result1;
}
private void requestCameraPermission(){
ActivityCompat.requestPermissions(this, cameraPermissions, CAMERA_REQUEST_CODE);
}
//handle permission results
public void onRequestPermissionResult(int requestCode, #NonNull String[] permission, #NonNull int[] grantResults){
switch (requestCode){
case CAMERA_REQUEST_CODE:{
if (grantResults.length>0){
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean storageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted && storageAccepted){
//both permission granted
pickFromCamera();
}
else{
//both or one permissions denied
Toast.makeText(this, "Camera & Storage permissions are required...", Toast.LENGTH_SHORT).show();
}
}
}
case STORAGE_REQUEST_CODE:{
if (grantResults.length>0){
boolean storageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (storageAccepted){
//permission granted
pickFromGallery();
}else{
//permission denied
Toast.makeText(this, "Storage permissions is required...", Toast.LENGTH_SHORT).show();
}
}
}
}
super.onRequestPermissionsResult(requestCode, permission, grantResults);
I do not know how to upload an image into Android Studio, I have looked into many videos in Youtube but I am not sure if I implement it correctly, since StartActivityForResult has been fabricated I try to follow the video in the Youtube how to implement it the new way, however it is not working. Can anyone help me with this?

Closing the "All files access" dialog when user allows access to all files in android

Presently, in my application, when the user is asked to provide "Access all files" permission, the dialog opens and remains on screen even when the user has allowed permission. Below provided screenshot shows the dialog I am referring to:-
I would like to add something in my code, which closes this dialog and opens target activity screen as soon as the user enables the toggle of "Allow access to all files".
GrantPermissionsActivity :-
public class GrantPermissionsActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_CODE = 1;
MaterialButton cancelMaterialButton, grantMaterialButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grant_permissions);
findViews();
initViews();
}
private void findViews() {
cancelMaterialButton = findViewById(R.id.materialButtonCancel);
grantMaterialButton = findViewById(R.id.materialButtonGrant);
}
private void initViews() {
if (checkPermission()){
Intent intent = new Intent(GrantPermissionsActivity.this,PasswordActivity.class);
}
cancelMaterialButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(GrantPermissionsActivity.this, "Need to give permission!", Toast.LENGTH_SHORT).show();
finish();
overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
});
grantMaterialButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkPermission()) {
Toast.makeText(GrantPermissionsActivity.this, "Permission already granted", Toast.LENGTH_SHORT).show();
} else if (!checkPermission()) {
requestPermission();
}
}
});
}
private boolean checkPermission() {
if (SDK_INT >= Build.VERSION_CODES.R) {
return Environment.isExternalStorageManager();
} else {
int result = ContextCompat.checkSelfPermission(GrantPermissionsActivity.this, READ_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(GrantPermissionsActivity.this, WRITE_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
}
}
private void requestPermission() {
if (SDK_INT >= Build.VERSION_CODES.R) {
try {
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
intent.addCategory("android.intent.category.DEFAULT");
intent.setData(Uri.parse(String.format("package:%s", getApplicationContext().getPackageName())));
startActivityForResult(intent, 2296);
} catch (Exception e) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivityForResult(intent, 2296);
}
} else {
//below android 11
ActivityCompat.requestPermissions(GrantPermissionsActivity.this, new String[]{WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
// perform action when allow permission success
Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Allow permission for storage access!", Toast.LENGTH_SHORT).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
Log.d(TAG, "onActivityResult: Reachedinresult");
if (requestCode == 2296 && resultCode == RESULT_OK) {
Log.d(TAG, "onActivityResult: Reached request code");
if (SDK_INT >= Build.VERSION_CODES.R) {
Log.d(TAG, "onActivityResult: Reached SDKINT");
if (Environment.isExternalStorageManager()) {
// perform action when allow permission success
/*Intent intent = new Intent(GrantPermissionsActivity.this,PasswordActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);*/
Log.d(TAG, "onActivityResult: Reached");
} else {
checkPermission();
Toast.makeText(this, "Permission not granted", Toast.LENGTH_SHORT).show();
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
Please let me know the changes in the above code.
Also, check the below sample for reference:-
Replace the method requestPermission() to
private void requestPermission() {
if (SDK_INT >= Build.VERSION_CODES.R) {
try {
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
intent.addCategory("android.intent.category.DEFAULT");
intent.setData(Uri.parse(String.format("package:%s", getApplicationContext().getPackageName())));
startActivityForResult(intent, 2296);
} catch (Exception e) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivityForResult(intent, 2296);
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if(Environment.isExternalStorageManager()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// perform action when allow permission success in android 11
}
});
this.cancel();
}
}
},2000,1000);
}
} else {
//below android 11
ActivityCompat.requestPermissions(GrantPermissionsActivity.this, new String[]{WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}}
If you want to start an activity from there, add flag Intent.FLAG_ACTIVITY_NEW_TASK in the Intent object, otherwise it may not work.

App quits after deliberately not giving location permission

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

Permission request dialog box appearing multiple times android

Check permission dialog box appears again and again inspite of giving permission and clicking all dialog box as accept it closes the app.
I have a helper method (copied from here) to check multiple permissions and see if any of them are not granted.
public static boolean hasPermissions(Context context, String... permissions) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.CAMERA};
if(!hasPermissions(this, PERMISSIONS)){
Log.d("permission","permission");
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}
I want it to load the same activity i.e. the MainActivity after granting permission.
Can anyone point why the permission is being asked multiple times.
Kind of late to this Party but give this code a try
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
} else {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 666); // Comment 26
}
}
onAvail();
onLoad();
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 666: // User selected Allowed 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();
snackbarView.setBackgroundColor(Color.WHITE);
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
// User selected the Never Ask Again Option Change settings in app settings manually
} else if (Build.VERSION.SDK_INT >= 23 && !shouldShowRequestPermissionRationale(permissions[0])) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this, R.style.MyAlertDialogStyle);
alertDialogBuilder.setTitle("Change Permissions in Settings");
alertDialogBuilder
.setMessage("Click SETTINGS to Manually Set\n\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);
}
});
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, R.style.MyAlertDialogStyle);
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) {
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;
}};
Just check that the permission you have mentioned here
String[] PERMISSIONS = {Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.CAMERA};
should be given in manifest file.
Please do the following changes in the corresponding places.
if (hasPermissions(this, PERMISSIONS)) {
// you have permissions
//Do your work.
}
replace **hasPermissions()** method with following code
public static boolean hasPermissions(Context context, String... permissions) {
int result;
List<String> listPermissionsNeeded = new ArrayList<>();
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
result = ContextCompat.checkSelfPermission(context, permission);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(permission);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), PERMISSION_ALL);
return false;
}
}
return true;
}
replace **onRequestPermissionsResult()** with following code
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
Log.d("requestCode", String.valueOf(requestCode));
switch (requestCode) {
case PERMISSION_ALL: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
//Do your work.
Toast.makeText(MainActivity.this, "Permission Recieved", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Until you grant the permission, we cannot proceed further", Toast.LENGTH_SHORT).show();
}
}
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}

Android check permission before Main activity

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).

Categories

Resources