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
Related
how do i make it so that when the user accepts location permission it will start working and no need to restart the app. At first on launch, my app will request location permission from the user, but even after they accept it will not run properly using these permissions. It will only work properly after restarting the app.
private void getLocationPermission() {
Log.d(TAG, "getLocationPermission: getting location permissions");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = true;
Log.d(TAG, "GRANTED");
initMap();
} else {
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
} else {
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}
private void getDeviceLocation() {
Log.d(TAG, "getDeviceLocation: getting the devices current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try {
if (mLocationPermissionsGranted) {
#SuppressLint("MissingPermission") final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Log.d(TAG, "onComplete: found location!");
Location currentLocation = (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()), DEFUALT_ZOOM,
"My Location");
} else {
Log.d(TAG, "onCOmplete: current location is null");
}
}
});
}
} catch (SecurityException e) {
Log.e(TAG, "getDeviceLocation: Security Exception: " + e.getMessage());
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
mLocationPermissionsGranted = false;
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE: {
if (grantResults.length > 0) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = false;
Log.d(TAG, "onRequestPermissionsResult: permission failed");
return;
}
}
mLocationPermissionsGranted = true;
Log.d(TAG, "onRequestPermissionsResult: permission granted");
initMap();
}
}
}
}
I want to save a GIF file (in android app) in internal or external storage. The file should then be found in the gallery. I downloaded the gif file via glide:
Glide.with(getContext())
.download(imageUrl)
.listener(new RequestListener<File>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<File> target, boolean isFirstResource) {
return false;
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public boolean onResourceReady(File resource, Object model, Target<File> target, DataSource dataSource, boolean isFirstResource) {
}
return false;
}
})
.submit();
your use ftech
implementation "com.tonyodev.fetch2:fetch2:3.0.10"
Androidx use:
implementation "androidx.tonyodev.fetch2:xfetch2:3.1.4"
download any file
if (isStoragePermissionGranted()) {
fetch = Fetch.Impl.getInstance(fetchConfiguration);
String url = nameFileDownload;
String file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + nameFileDownload.substring(url.lastIndexOf('/') + 1);
;
if (fileExist(file)) {
view(null, nameFileDownload.substring(url.lastIndexOf('/') + 1));
} else {
progress_download.setVisibility(View.VISIBLE);
btn_download.setVisibility(View.GONE);
final com.tonyodev.fetch2.Request request = new com.tonyodev.fetch2.Request(url, file);
request.setPriority(Priority.NORMAL);
request.setNetworkType(NetworkType.ALL);
fetch.enqueue(request, updatedRequest -> {
fetch.addListener(fetchListener);
//Request was successfully enqueued for download.
}, error -> {
progress_download.setVisibility(View.GONE);
btn_download.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "feild", Toast.LENGTH_SHORT).show();
//An error occurred enqueuing the request.
});
}
} else {
Toast.makeText(MainActivity.this, "perssion denid", Toast.LENGTH_SHORT).show();
}
}
isStoragePermissionGranted:
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v("TAG", "Permission is granted");
return true;
} else {
Log.v("TAG", "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
} else { //permission is automatically granted on sdk<23 upon installation
Log.v("TAG", "Permission is granted");
return true;
}
}
manifests:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
I want Save text speech as audio file with pause 5 seconds silent.I am aable to save text to mp3 file .I tried but i did not get anywhere .
Code to save text to mp3 file.i need to add silent 5 seconds.
HashMap<String, String> myHashRender = new HashMap();
String text="Name ,How are you.";//After Name i need to stop 5 seconds silent
String destFileName = Environment.getExternalStorageDirectory()+"/myfolder/tts.mp3";
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, text);
tts.synthesizeToFile(text, myHashRender, destFileName);
// TAKE PERMISSIONS RUNTIME TOO
private void requestPermission() {
ActivityCompat.requestPermissions(MainActivity.this, new
String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length> 0) {
boolean StoragePermission = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;
if (StoragePermission && RecordPermission) {
Toast.makeText(MainActivity.this, "Permission Granted",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this,"Permission
Denied",Toast.LENGTH_LONG).show();
}
}
break;
}
}
public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(),
WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(),
RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED;
}
//Prepare RECORDER
String outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";
private MediaRecorder myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
// START THE RECORDING
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
// START YOUR TEXT_TO_SPEECH HERE
} catch (IllegalStateException ise) {
// make something ...
} catch (IOException ioe) {
// make something
}
Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
// NOW TO STOP OR TO SAVE USE BELOW CODE
// when TTS is done playing, the OnUtteranceCompletedListener() get called automatically, for this your activity needs to IMPLEMENTS OnUtteranceCompletedListener
// It's callback // After 5 sec of TTS's speaking, file have saved
public void onUtteranceCompleted(String utteranceId) {
Log.i(TAG, utteranceId); //utteranceId == "SOME MESSAGE"
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
myAudioRecorder.stop();
myAudioRecorder.release();
myAudioRecorder = null;
Toast.makeText(getApplicationContext(), "Audio Recorder successfully", Toast.LENGTH_LONG).show();
}
}, 5000);
}
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 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
}
}