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"/>
Related
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'm currently having an issue with runtime permissions while using the HiPermission library.I'm asking the user to grant the permission to read/write external storage but even though I accept the permission I still get this error when I try to open an image from the gallery. When the application starts there is a permission check to see if the user has accepted the permissions.To access the image the user need to use a button which also has a permission check
private boolean checkAllPermissions(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int permissionCheck = PackageManager.PERMISSION_GRANTED;
String[] requestedPermissions = new String[]
{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA};
for (String permission : requestedPermissions) {
permissionCheck = permissionCheck + ContextCompat.checkSelfPermission(getContext(), permission);
}
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
makeText(getActivity(),R.string.actvt_main_tst_request_permission_all, Toast.LENGTH_LONG).show();
return false;
}
}
return true;
}
This is the error I get:
E/BitmapFactory: Unable to decode stream:
java.io.FileNotFoundException:
/storage/emulated/0/Download/download.png (Permission denied)
It's weird though because if I restart the application everything works fine.
public void requestAllPermissions(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
List<PermissionItem> permissionItems = new ArrayList<PermissionItem>();
permissionItems.add(new PermissionItem(Manifest.permission.CAMERA, "Camera", R.drawable.permission_ic_camera));
permissionItems.add(new PermissionItem(Manifest.permission.WRITE_EXTERNAL_STORAGE, "Storage", R.drawable.permission_ic_storage));
HiPermission.create(MainActivity.this)
.title("Welcome to App")
.msg(getString(R.string.permis_req))
.permissions(permissionItems)
.animStyle(R.style.PermissionAnimScale)
.checkMutiPermission(new PermissionCallback() {
#Override
public void onClose() {
Log.i(TAG, "onClose");
Toast.makeText(getApplicationContext(), "They cancelled our request", Toast.LENGTH_SHORT);
}
#Override
public void onFinish() {
Log.wtf("finished","finished");
Toast.makeText(getApplicationContext(), "All permissions requested completed", Toast.LENGTH_SHORT);
System.exit(0);
}
#Override
public void onDeny(String permission, int position) {
Log.i(TAG, "onDeny");
}
#Override
public void onGuarantee(String permission, int position) {
Log.i(TAG, "onGuarantee");
}
});
}
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
}
}
}
}
}
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
}
}