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();
Related
My Topic,
i am trying to take storage permission in android, my permission code works in below andoid 11 ,
but problem is when i try to take storage permission in android 11 then code not works , so please help me..
This is my code:-
This is my AndroidManifest.xml Code
android:requestLegacyExternalStorage="true"
This is my JavaCode Code
#Override
protected void onActivityResult(int _requestCode, int _resultCode, Intent _data) {
super.onActivityResult(_requestCode, _resultCode, _data);
if (_resultCode == RESULT_OK){
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R){
if (Environment.isExternalStorageManager()){
Toast.makeText(this,"Permission Granted",Toast.LENGTH_SHORT).show();
i.setClass(getApplicationContext(), Main2Activity.class);
startActivity(i);
} else {
_takePermission();
}
}
}
switch (_requestCode) {
default:
break;
}
}
public boolean _isPermissionGranted() {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.R){
return Environment.isExternalStorageManager();
} else {
int readexternalStoragePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
return readexternalStoragePermission == PackageManager.PERMISSION_GRANTED;
}
}
public void _takePermission() {
if (Build.VERSION.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,100);
} catch (Exception exception){
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivityForResult(intent,100);
}
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},101);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0){
if (requestCode == 101){
boolean readExternalStorage = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (readExternalStorage){
Toast.makeText(this,"Permission Granted",Toast.LENGTH_SHORT).show();
i.setClass(getApplicationContext(), Main2Activity.class);
startActivity(i);
} else {
_takePermission();
}
}
}
Above is the complete code, please check and tell me what my mistake is, and what is the correct bridge.
Thanks for watching..
android:requestLegacyExternalStorage="true" will not affect if your app targetSdk > 30 (Android 11 and above).
Must add this to manifest:
Request to permission:
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.MANAGE_EXTERNAL_STORAGE}, 1);
Check whether app can access storage:
if (!Environment.isExternalStorageManager())
Request to access "All files and media" access:
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
Uri uri = Uri.fromParts("package", this.getPackageName(), null);
intent.setData(uri);
startActivity(intent);
I want to delete an image file from storage but it returns false.
I created in my app, I can delete it but when I reinstall my app I can show it but I can't delete it
Here's my code:
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
File file = new File(cartPostalDbs.get(position).getFilePath());
boolean deleted = file.delete();
if (deleted) {
cartPostalDbs.remove(mPos);
notifyDataSetChanged();
} else {
Toast.makeText(context, "Can Not Delete File", Toast.LENGTH_SHORT).show();
}
}
Here's my file path
/storage/emulated/0/Pictures/yadim/1/1558.jpg
and I check PERMISSION and use this permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
That's what you need, it works in multiple cases:
•If you want to delete a directory ( folder )
•If the file/directory that you want to delete doesn't exist
here is the code:
public void deleteFile(String path) {
File file = new File(path);
if (!file.exists()) return;
if (file.isFile()) {
file.delete();
return;
}
File[] fileArr = file.listFiles();
if (fileArr != null) {
for (File subFile : fileArr) {
if (subFile.isDirectory()) {
deleteFile(subFile.getAbsolutePath());
}
if (subFile.isFile()) {
subFile.delete();
}
}
}
file.delete();
}
usage:
deleteFile(cartPostalDbs.get(position).getFilePath());
your final code should look like this:
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_GRANTED) {
try {
deleteFile(cartPostalDbs.get(position).getFilePath());
boolean deleted = true;
} catch ( Exception e ) { boolean deleted = false; }
if (deleted) {
cartPostalDbs.remove(mPos);
notifyDataSetChanged();
} else {
Toast.makeText(context, "Can Not Delete File",
Toast.LENGTH_SHORT).show();
}
}
EDIT 1:
I tried to edit the code to request the permission if it isn't granted :
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
try {
deleteFile(cartPostalDbs.get(position).getFilePath());
boolean deleted = true;
} catch ( Exception e ) { boolean deleted = false; }
if (deleted) {
cartPostalDbs.remove(mPos);
notifyDataSetChanged();
} else {
requestPermissions(new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
}
}
Add the onActivityResult void to delete the file when the permission is granted :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1000:
if (resultCode == Activity.RESULT_OK) {
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_GRANTED) {
try {
deleteFile(cartPostalDbs.get(position).getFilePath());
boolean deleted = true;
} catch ( Exception e ) { boolean deleted = false; }
if (deleted) {
cartPostalDbs.remove(mPos);
notifyDataSetChanged();
} else {
Toast.makeText(context, "Can Not Delete File", Toast.LENGTH_SHORT).show();
}
}
} else {
Toast.makeText(context, "Can Not Delete File", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
Also don't forget to add the permission to the AndroidManifest.xml file
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
}
}
}
}
}
I am trying to attach a pdf file with my Gmail. But the problem is, it always shows a toast message which says "PERMISSION DENIED FOR THE ATTACHMENT". I tried on some different emails like Yahoo, but the file is still not being attached.
This is my Code for the Attachment:
case R.id.emailPdf:
try {
String filename = "SampleFile1.pdf";
File filelocation = new File(Environment.getDataDirectory() + "/data/" + getPackageName() + "/files/", filename);
filelocation.setReadable(true, false);
Uri path = Uri.fromFile(filelocation);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("vnd.android.cursor.dir/email");
String to[] = {""};
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(Intent.EXTRA_STREAM, path);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(Intent.createChooser(emailIntent, "Send email..."), 12);
break;
}catch (Exception e){
e.printStackTrace();
}
These are the permissions in the AndroidManifest.xml file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I used the debugger, and I observed that the file is being read from the file location but dont know why its not getting attached.
Any help would be appreciated.
Thanks in advance.
Try like below:
Create method to check runtime permission.
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public boolean checkExternalPermission() {
int currentAPIVersion = Build.VERSION.SDK_INT;
if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getActivity());
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("Write external storage permission is necessary to read gallery pictures!!!");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity) getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
Now on attach button click:
boolean result = checkExternalPermission();
if (result) {
activeGallery();
}
Create method to open gallery like below:
/**
* to gallery
*/
private void activeGallery() {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
Now handle permission result like below:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
activeGallery();
} else {
Toast.makeText(getActivity(), "Permission not granted", Toast.LENGTH_LONG).show();
//code for deny
}
break;
}
}
Now handle activity result like below for your selected attachment:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (resultCode == RESULT_OK && null != data) {
try {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver()
.query(selectedImage, filePathColumn, null, null,
null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
// MyImage image = new MyImage();
// image.setTitle("Test");
// image.setDescription(
// "test choose a photo from gallery and add it to " +
// "list view");
// image.setDatetime(System.currentTimeMillis());
File file = new File(picturePath);
Uri imageUri = Uri.fromFile(file);
Product product = new Product(catID, "custom", "#1111", imageUri.toString(), "15000", "30%", 0);
dBhelper.createPRODUCT(product);
imageList.add(0, product);
// imageList.add(0, imageUri);
setimage(imageUri.toString(), imgview, true);
// imageList.add(0, picturePath);
adapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
// images.add(image);
}
break;
}
}
And finally declare below global variable:
private static final int RESULT_LOAD_IMAGE = 1;
public static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 3;
Make sure below permission you have define in manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
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
}
}