I use this function to give permission from the user :
private void askForPermission(String permission, Integer requestCode)
{
if (ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permission)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
}
} else {
Toast.makeText(this,"we have", Toast.LENGTH_SHORT).show();
}
}
And I add this Code to Manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
And I called this in onCreate():
#Override
protected void onCreate(Bundle savedInstanceState)
{
askForPermission(Manifest.permission.ACCESS_FINE_LOCATION,LOCATION);
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
}
the user allows, but when I Check with if in next line, return to me Permission deny!
i want to give the current location.
where is my mistake?
You need to check permission in onRequestPermissionsResult() it called when user click on allow or deny button
final String[] NECESSARY_PERMISSIONS = new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
};
if ((ContextCompat.checkSelfPermission(DialerHomeActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)) {
//Granted
} else {
// ask for permission
ActivityCompat.requestPermissions(DialerHomeActivity.this,
NECESSARY_PERMISSIONS, 123);
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 123:
if (grantResults.length > 0) {
if ((grantResults[0] == PackageManager.PERMISSION_GRANTED))) {
//Permission granted
} else {
if ((grantResults[0] == PackageManager.PERMISSION_DENIED && !ActivityCompat
.shouldShowRequestPermissionRationale(
getApplicationContext(),
Manifest.permission.ACCESS_FINE_LOCATION))) {
//Permission deny with never ask again
} else {
//Permission deny
}
}
}
}
}
Related
I'm trying to make an activity request for location related permissions by using the code below but when I run the code, it doesn't ask the user for permission for some reason. I added the permissions in the manifest file for both coarse location and fine location. When I open up the activity, it doesn't request the user to enable locations related permissions. I'm not sure why that is and I would appreciate any help.
final int COARSE_LOCATION = 99, FINE_LOCATION = 100;
...
#Override
protected void onStart() {
super.onStart();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, FINE_LOCATION);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, FINE_LOCATION);
}
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, COARSE_LOCATION);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, COARSE_LOCATION);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case FINE_LOCATION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLastLocation();
} else {
Toast.makeText(ContactListPage.this,"wrong permission",Toast.LENGTH_SHORT).show();
}
}
}
private void getLastLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Task<Location> locationTask = fusedLocationProviderClient.getLastLocation();
locationTask.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
Toast.makeText(ContactListPage.this,"Lat: " + latitude,Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(ContactListPage.this,"location was null",Toast.LENGTH_SHORT).show();
}
}
});
locationTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ContactListPage.this,"error getting last location",Toast.LENGTH_SHORT).show();
}
});
}
When I try to create a directory in storage/emulator/0/ directory, it becomes invisible and inaccessible. I use mkdir() to create, and when I check its existence, dir.exists() returns true, even though I cannot access it.
My device runs in API 23, so I get the permissions in runtime, like this:
boolean hasPermission = (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermission) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_READ_STORAGE);
}
I also create onRequestPermissionsResult function:
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case REQUEST_READ_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//reload my activity with permission granted or use the features what required the permission
} else
{
Toast.makeText(this, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
In this function, I try to access my directory
public void makeOutSide(String song, InputStream ins){
// Create the directory
File dir = new File(Environment.getExternalStorageDirectory(),"appMemes");
// If it does not exists, make it.
if (!dir.exists()) {
dir.mkdirs(); // Generating the directory
}
try {
// Open the resource
byte[] buffer = new byte[ins.available()];
ins.read(buffer);
ins.close();
// Burn
String filename = Environment.getExternalStorageDirectory()
+ "/appMemes/"+song+".mp3";
FileOutputStream fos = new FileOutputStream(filename);
fos.write(buffer);
fos.close();
} catch (Exception e) {
System.out.println(e);
}
}
My AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.renan.appmemes">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
...
</application>
first put EnableRuntimePermission Function in Oncreate
private void EnableRuntimePermission() {
if (ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale
(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(MainActivity.this, "Allow permissions", Toast.LENGTH_LONG).show();
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(
new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, RequestPermissionCode);
}
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length > 0) {
boolean writeExternalFile = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (writeExternalFile) {
} else {
Toast.makeText(MainActivity.this, "Allow permissions to Edit the Image", Toast.LENGTH_LONG).show();
}
}
break;
}
}
then create direcory using this line
File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/DSLR CAMERASagar/");
dir.mkdirs();
I am creating an app in which i am unable to handle the permission of location in fragment.The method
public void onRequestPermissionsResult(int requestCode String permissions[], int[] grantResults){}
is not working in fragment. So please help me how to handle both permission DENY and ALLOW This is my code...
public class BlankFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_blank, container, false);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
return v;
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(),
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.
if (ActivityCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(getActivity(), "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
}
Please help me how to handle the both permissions in fragment.
Thanks..
AFAIK, you should use this PermissionsDispatcher to request runtime permission. You just need to define callback functions in your Fragment as below:
#NeedsPermission(Manifest.permission. ACCESS_FINE_LOCATION)
void showCamera() {
getSupportFragmentManager().beginTransaction()
.replace(R.id.sample_content_fragment, CameraPreviewFragment.newInstance())
.addToBackStack("camera")
.commitAllowingStateLoss();
}
#OnShowRationale(Manifest.permission. ACCESS_FINE_LOCATION)
void showRationaleForCamera(final PermissionRequest request) {
new AlertDialog.Builder(this)
.setMessage(R.string.permission_camera_rationale)
.setPositiveButton(R.string.button_allow, (dialog, button) -> request.proceed())
.setNegativeButton(R.string.button_deny, (dialog, button) -> request.cancel())
.show();
}
#OnPermissionDenied(Manifest.permission. ACCESS_FINE_LOCATION)
void showDeniedForCamera() {
Toast.makeText(this, R.string.permission_camera_denied, Toast.LENGTH_SHORT).show();
}
#OnNeverAskAgain(Manifest.permission. ACCESS_FINE_LOCATION)
void showNeverAskForCamera() {
Toast.makeText(this, R.string.permission_camera_neverask, Toast.LENGTH_SHORT).show();
}
Then using the auto-gen method to request permission:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button_camera).setOnClickListener(v -> {
// NOTE: delegate the permission handling to generated method
MainActivityPermissionsDispatcher.showCameraWithCheck(this);
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// NOTE: delegate the permission handling to generated method
MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
}
You should read the library carefully for more detail.
Try this after removing ActivityCompat from code.
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)) {
//Prompt the user once explanation has been shown
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
im trying to show multiple permission request on Android 7.0
This code working with no problem on Android sdk 23.
SDK 24 showing one time the request, if i touch allow or denied button, this code working one time and Don't show other request.
Code is here;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
if (checkSelfPermission(Manifest.permission.READ_SMS) == PackageManager.PERMISSION_DENIED) {
requestPermissions(new String[]{Manifest.permission.READ_SMS}, 1);
}
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
}
try this
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_SMS, Manifest.permission.ACCESS_FINE_LOCATION};
boolean flag = false;
for (int i = 0; i < permissions.length; i++) {
if (checkSelfPermission(permissions[i]) == PackageManager.PERMISSION_DENIED) {
flag = true;
break;
}
}
if (flag) {
requestPermissions(permissions, 1);
}
}
First of all check if permission is already granted and if not granted then ask for permission using below code.
String[] PERMISSIONS = {Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_CALL_LOG, Manifest.permission.READ_CONTACTS,
Manifest.permission.WRITE_CONTACTS};
if (!hasPermissions(this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}
Once permissions are granted, you can execute below code to check whether a particular permission was granted or denied
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_ALL: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
}
if (grantResults[1] == PackageManager.PERMISSION_GRANTED) {
} else {
}
if (grantResults[2] == PackageManager.PERMISSION_GRANTED) {
} else {
}
if (grantResults[3] == PackageManager.PERMISSION_GRANTED) {
} else {
}
if (grantResults[4] == PackageManager.PERMISSION_GRANTED) {
} else {
}
} else {
//All permission denied
}
runAfterPermissionGranted();
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
i want to ask the user to accept the following permissions at the same time(one by one), the permissions are like:
checkLocationPermission, checkReadSMS, checkCallingPermission, checkReadState, checkContactWriteState.
So, how i can ask all these permissions in my first screen itself.
Please help me out in this regard.
Thanks in advance.
You have to first check that user phone build version is 23.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
askPermissions(true);
} else {
startActivity(new Intent(PermissionsActivity.this, SplashActivity.class));
finish();
}
If version is 23 then you need to ask permissions.
private void askPermissions(boolean isForOpen) {
isRationale = false;
List permissionsRequired = new ArrayList();
final List<String> permissionsList = new ArrayList<String>();
if (!checkPermission(permissionsList, Manifest.permission.WRITE_EXTERNAL_STORAGE))
permissionsRequired.add("Write External Storage");
if (!checkPermission(permissionsList, Manifest.permission.CALL_PHONE))
permissionsRequired.add("Call phone");
if (!checkPermission(permissionsList, Manifest.permission.READ_PHONE_STATE))
permissionsRequired.add("Read phone state");
if (!checkPermission(permissionsList, Manifest.permission.READ_CONTACTS))
permissionsRequired.add("Read Contacts");
if (!checkPermission(permissionsList, Manifest.permission.RECEIVE_SMS))
permissionsRequired.add("Receive SMS");
if (!checkPermission(permissionsList, Manifest.permission.GET_ACCOUNTS))
permissionsRequired.add("Get Accounts");
if (!checkPermission(permissionsList, Manifest.permission.ACCESS_COARSE_LOCATION))
permissionsRequired.add("Location");
if (!checkPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION))
permissionsRequired.add("Location");
if (permissionsList.size() > 0 && !isRationale) {
if (permissionsRequired.size() > 0) {
}
if (isForOpen) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ActivityCompat.requestPermissions(this, permissionsList.toArray(new String[permissionsList.size()]),
11);
}
}
} else if (isRationale) {
if (isForOpen) {
new android.support.v7.app.AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle)
.setTitle("Permission Alert")
.setMessage("You need to grant permissions manually. Go to permission and grant all permissions.")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, 123);
}
})
.show();
}
} else {
startActivity(new Intent(PermissionsActivity.this, SplashActivity.class));
finish();
}
}
private boolean checkPermission(List permissionsList, String permission) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
// Check for Rationale Option
if (!isFirst) {
if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
isRationale = true;
return false;
}
}
}
}
return true;
}
on the onRequestPermissionsResult you need to check which permissions granted
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 11:
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.CALL_PHONE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_CONTACTS, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.RECEIVE_SMS, PackageManager.PERMISSION_GRANTED);
// Fill with results
for (int i = 0; i < permissions.length; i++) {
perms.put(permissions[i], grantResults[i]);
}
// Check for ACCESS_FINE_LOCATION
if (perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
perms.get(Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED &&
perms.get(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED &&
perms.get(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED &&
perms.get(Manifest.permission.RECEIVE_SMS) == PackageManager.PERMISSION_GRANTED) {
// All Permissions Granted
startActivity(new Intent(PermissionsActivity.this, SplashActivity.class));
finish();
} else {
// Permission Denied
Toast.makeText(this, "Some Permission is Denied.", Toast.LENGTH_SHORT)
.show();
isFirst = false;
askPermissions(true);
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
If user has set the permission to never ask again then the application setting screen will open. User will allow/Deny permission there. You need to check again on the activityResult.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
askPermissions(true);
}
if (!hasPermissions()){
// your app doesn't have permissions, ask for them.
requestNecessaryPermissions();
}
else {
// your app already have permissions allowed.
// do what you want.
}
private boolean hasPermissions() {
int res = 0;
// list all permissions which you want to check are granted or not.
String[] permissions = new String[] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
for (String perms : permissions){
res = checkCallingOrSelfPermission(perms);
if (!(res == PackageManager.PERMISSION_GRANTED)){
// it return false because your app dosen't have permissions.
return false;
}
}
// it return true, your app has permissions.
return true;
}
private void requestNecessaryPermissions() {
// make array of permissions which you want to ask from user.
String[] permissions = new String[] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// have arry for permissions to requestPermissions method.
// and also send unique Request code.
requestPermissions(permissions, REQUEST_CODE_STORAGE_PERMS);
}
}
/* when user grant or deny permission then your app will check in
onRequestPermissionsReqult about user's response. */
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grandResults) {
// this boolean will tell us that user granted permission or not.
boolean allowed = true;
switch (requestCode) {
case REQUEST_CODE_STORAGE_PERMS:
for (int res : grandResults) {
// if user granted all required permissions then 'allowed' will return true.
allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
}
break;
default:
// if user denied then 'allowed' return false.
allowed = false;
break;
}
if (allowed) {
// if user granted permissions then do your work.
dispatchTakePictureIntent();
}
else {
// else give any custom waring message.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
Toast.makeText(MainActivity.this, "Camera Permissions denied", Toast.LENGTH_SHORT).show();
}
else if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(MainActivity.this, "Storage Permissions denied", Toast.LENGTH_SHORT).show();
}
}
}
}
follow this tutorial, in this tutorial multiples permissions are asked
Android 6.0 Runtime Permissions
the Kotlin version
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.fragment.app.Fragment
class MyFragment : Fragment() {
companion object {
val TAG: String = MyFragment::class.java.simpleName
var PERMISSIONS = arrayOf(
Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
}
private val permReqLauncher =
registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
val granted = permissions.entries.all {
it.value == true
}
if (granted) {
displayCameraFragment()
}
}
private fun takePhoto() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
displayCameraFragment()
}
activity?.let {
if (hasPermissions(activity as Context, PERMISSIONS)) {
displayCameraFragment()
} else {
permReqLauncher.launch(
PERMISSIONS
)
}
}
}
// util method
private fun hasPermissions(context: Context, permissions: Array<String>): Boolean = permissions.all {
ActivityCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
}
private fun displayCameraFragment() {
// open camera fragment
}
}