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
}
}
Related
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
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
}
I want to open camera when clicking an item on my dialog box, but I get an error like below. I've been adding a camera permission to manifest.xml.
java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.IMAGE_CAPTURE cmp=com.sonyericsson.android.camera/.MultiWindowActivity } from ProcessRecord{b42fcde 29884:ukmutilizer.project.com.ukm_utilizer/u0a273} (pid=29884, uid=10273) with revoked permission android.permission.CAMERA
this is my function
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.personal_data_step, container, false);
ButterKnife.bind(this, view);
imageEktp.setClickable(true);
imageEktp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Log.d("test : ", "testing");
CharSequence menu[] = new CharSequence[]{"Take From Galery", "Open Camera"};
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Pick a Picture");
builder.setItems(menu, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0){
Toast.makeText(getActivity(), "galery", Toast.LENGTH_SHORT).show();
}else{
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivity(intent);
}
}
});
builder.show();
}
});
return view;
}
Ensure you request Runtime Camera Permission from the user.
private static final int CAMERA_REQUEST_CODE = 100;
Request permission if not granted.
if (checkSelfPermission(Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA},
CAMERA_REQUEST_CODE);
}
Do stuff inside onRequestPermissionsResult.
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == CAMERA_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Camera permission granted.", Toast.LENGTH_LONG).show();
// Do stuff here for Action Image Capture.
} else {
Toast.makeText(this, "Camera permission denied.", Toast.LENGTH_LONG).show();
}
}
}
Also this should be declared inside Manifest as well.
You have to get runtime permission then only access your camera
like
in manifest
<uses-permission android:name="android.permission.CAMERA" />
in Java
private static final int MY_CAMERA_REQUEST_CODE = 100;
private void processPickImage() {
if(hasCameraPermission()) {
pickImage();
}
else
{
requestCameraPermission();
}
}
private boolean hasCameraPermission() {
return ContextCompat.checkSelfPermission(context,
Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
}
#TargetApi(Build.VERSION_CODES.M)
private void requestCameraPermission() {
requestPermissions(new String[]{Manifest.permission.CAMERA},
MY_CAMERA_REQUEST_CODE );
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
switch (requestCode) {
case MY_CAMERA_REQUEST_CODE :
processPickImage();
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
The user has to confirm the permission request.
Try
public class ActivityMain extends AppCompatActivity
{
public static final int MY_PERMISSIONS_REQUEST = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
if (ContextCompat.checkSelfPermission(ActivityMain.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{ ActivityCompat.requestPermissions(ActivityMain.this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST);
}
[...]
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
{ switch (requestCode)
{ case MY_PERMISSIONS_REQUEST:
[...]
}
}
}
when you run your app in 6.0 above like marshmallow device then need permission other wise no need to permission.
that time your code work..
if run marshmallow device that time need permission then make below code ..
private void alertDialog(){
CharSequence menu[] = new CharSequence[]{"Take From Galery", "Open Camera"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a Picture");
builder.setItems(menu, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0){
Toast.makeText(getApplicationContext(), "galery", Toast.LENGTH_SHORT).show();
}else{
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivity(intent);
}
}
});
builder.show();
}
then above method put in permission code like below ..
if (ContextCompat.checkSelfPermission(webView.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(webView.this, Manifest.permission.CAMERA)) {
alertDialog();
}
else{
ActivityCompat.requestPermissions(webView.this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
}
add two permission into manifest file ..
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
your error main problem is permission if you add this below line is work.
if (ContextCompat.checkSelfPermission(webView.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(webView.this, Manifest.permission.CAMERA)) {
alertDialog();
}
else{
ActivityCompat.requestPermissions(webView.this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
}
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);
}
}
this is my code for get permissions...but still its stop when user perform permission action(target api is 25). any other way?
boolean isMdevice;
boolean pstatus;
int code=1;
String[] perms = { android.Manifest.permission.RECEIVE_SMS, Manifest.permission.CALL_PHONE, Manifest.permission.SEND_SMS};
/////then in oncreate
isMdevice=isMarshmallowPlusDevice();
pstatus= isPermissionRequestRequired(MainActivity.this, perms, code);
////then methods
public static boolean isMarshmallowPlusDevice() {
return Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1;
}
#TargetApi(Build.VERSION_CODES.M)
public static boolean isPermissionRequestRequired(Activity activity, #NonNull String[] permissions, int requestCode) {
if (isMarshmallowPlusDevice() && permissions.length > 0) {
List<String> newPermissionList = new ArrayList<>();
for (String permission : permissions) {
if (PERMISSION_GRANTED != activity.checkSelfPermission(permission)) {
newPermissionList.add(permission);
}
}
if (newPermissionList.size() > 0) {
activity.requestPermissions(newPermissionList.toArray(new String[newPermissionList.size()]), requestCode);
return true;
}
}
return false;
}
try this code for Check permission and ask for runtime permission:
Add this class to your project
public class PermissionUtils {
public static boolean checkPermission(Context context, String permission) {
return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
}
public static void requestPermissions(Activity activity, String messageInCaseOfCustomDialog, int permissionId, String... permissions) {
/* if (o instanceof Fragment) {
FragmentCompat.requestPermissions((Fragment) o, permissions, permissionId);
} else */
if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
permissions[0])) {
showCustomDialogForAskPermission(activity, messageInCaseOfCustomDialog, permissionId, permissions);
// 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 if (/*MySharedPreference.getSharedPrefrence(activity).getBoolean(permissions[0], false)*/) { //Use your Shared Preference
// No explanation needed, we can request the permission.
showCustomDialogForGoToTheSettings(activity, messageInCaseOfCustomDialog);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
} else {
ActivityCompat.requestPermissions(activity, permissions, permissionId);
}
/*MySharedPreference.getSharedPrefrence(activity).edit().putBoolean(permissions[0], true).commit();*/ //Use your Shared Preference
}
private static void showCustomDialogForGoToTheSettings(final Activity activity, String message) {
AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
dialog.setTitle("Permission Required");
dialog.setMessage(message);
dialog.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", activity.getPackageName(), null);
intent.setData(uri);
activity.startActivity(intent);
}
});
dialog.show();
}
private static void showCustomDialogForAskPermission(final Activity activity, String message, final int permissionId, final String... permissions) {
AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
dialog.setTitle("Permission Required");
dialog.setMessage(message);
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(activity, permissions, permissionId);
}
});
dialog.show();
}
}
Now you can directly check if you have that permission or not,Suppose you want to check for READ_EXTERNAL_STORAGE permission
if (PermissionUtils.checkPermission(RegisterScreenActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//Do your work
} else {PermissionUtils.requestPermissions(RegisterScreenActivity.this, "You need to provide storage permission for this service", 101, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE});//ask for permission
}
You can also track its result in onRequestPermissionsResult() methods like
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 101:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//permission granted, can do your work
} else {
//permission not granted
}
break;
}
}