SecurityException: Permission Denial on reading file from Downloads - android

There are some similar questions on StackOverflow but the situations they happened a little bit different.
I need to read a file (in Service) that user shared with a standard share mechanism.
There are no problems reading files from gallery or files shared by File Managers or Google Drive. But there are problems when I try to share files from Downloads.
I receive:
java.lang.SecurityException: Permission Denial: opening provider
com.android.providers.downloads.DownloadStorageProvider from
ProcessRecord{432abf50 8550:clipboard.clipboardtest/u0a167} (pid=8550,
uid=10167) requires android.permission.MANAGE_DOCUMENTS or
android.permission.MANAGE_DOCUMENTS
My manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="virtualclipboard.copytodesktop"
android:installLocation="internalOnly">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS" />
<uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER" />
<uses-permission android:name="android.permission.ACCESS_ALL_DOWNLOADS" />
<uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER_ADVANCED" />
<application>
...
</application>
</manifest>
The code to read a file. I receive Uri in intent while share operation.
InputStream input = getContentResolver().openInputStream(fileUri);
byte[] fileData = Converter.InputStreamToByteArray(input);
// ...
public class Converter {
public static byte[] InputStreamToByteArray(InputStream inputStream) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int reads = inputStream.read();
while(reads != -1){
baos.write(reads);
reads = inputStream.read();
}
return baos.toByteArray();
}
catch (Exception e) {
return null;
}
}
}
Reproduced on Nexus 5, 4.4.4, KitKat.

Related

Error when self updating an android application

I have downloaded the apk file that I need successfully. To try if the apk file that I have downloaded is not corrupted and can be installed correctly, I manually click the complete downloaded apk file to update my application and it installs right. Going further, I am trying to install the update automatically. Meaning, as soon as the file is downloaded completely, I want the application to update itself. The application that downloads the file is the same application that will be updated by the updated apk. This should work like the Google In-App update but without the Google Play Store. With the application that downloaded the file is running and by manually tapping the downloaded file, I can still install the update to this application without issues. It's just that, when I try to do this automatically, it gives the error like so:
FATAL EXCEPTION: AsyncTask #1
Process: com.google.android.packageinstaller, PID: 15764
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:325)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.SecurityException: Permission Denial: opening provider androidx.core.content.FileProvider from ProcessRecord{f4c3105 15764:com.google.android.packageinstaller/u0a18} (pid=15764, uid=10018) that is not exported from uid 10099
at android.os.Parcel.readException(Parcel.java:1684)
at android.os.Parcel.readException(Parcel.java:1637)
at android.app.ActivityManagerProxy.getContentProvider(ActivityManagerNative.java:4199)
at android.app.ActivityThread.acquireProvider(ActivityThread.java:5508)
at android.app.ContextImpl$ApplicationContentResolver.acquireUnstableProvider(ContextImpl.java:2239)
at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1520)
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1133)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:986)
at android.content.ContentResolver.openInputStream(ContentResolver.java:706)
at com.android.packageinstaller.PackageInstallerActivity$StagingAsyncTask.doInBackground(PackageInstallerActivity.java:792)
at com.android.packageinstaller.PackageInstallerActivity$StagingAsyncTask.doInBackground(PackageInstallerActivity.java:783)
at android.os.AsyncTask$2.call(AsyncTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
at java.lang.Thread.run(Thread.java:761) 
This is how I implement the opening and attempt to install the update
private void openDownloadedAttachment(final Context context, final long downloadId, Uri uri) {
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
#SuppressLint("Range")
int downloadStatus = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
#SuppressLint("Range")
String downloadLocalUri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
#SuppressLint("Range")
String downloadMimeType = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE));
if ((downloadStatus == DownloadManager.STATUS_SUCCESSFUL) && downloadLocalUri != null) {
try {
downloadLocalUri = "/storage/emulated/0/AATv2.apk";
openDownloadedAttachment(context, Uri.parse(downloadLocalUri), downloadMimeType);
Intent promptInstall = new Intent(Intent.ACTION_VIEW);
promptInstall.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
promptInstall.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
promptInstall.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION );
File file = new File(downloadLocalUri);
uri = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName()+".provider",
file);
promptInstall.setDataAndType(uri,
"application/vnd.android.package-archive");
promptInstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(promptInstall);
}
catch (ActivityNotFoundException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
cursor.close();
}
AndroidManifest
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INSTALL_PACKAGES"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.DELETE_PACKAGES"
tools:ignore="ProtectedPermissions" />
<application>
.....
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>
</application>
provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
This is your problem:
Intent promptInstall = new Intent(Intent.ACTION_VIEW);
promptInstall.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
promptInstall.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
promptInstall.setFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION );
You need to call addFlags() instead of setFlags(). When you call addFlags() this adds the flags you specify to the flags that are already set in the Intent. When you call setFlags() this overwrites the flags that are already set in the Intent with the flags you specify.
In your code, the last call to setFlags() sets FLAG_GRANT_PERSISTABLE_URI_PERMISSION but the other flags (FLAG_GRANT_READ_URI_PERMISSION, FLAG_GRANT_WRITE_URI_PERMISSION) are cleared.

Android 12 - CAMERA2 - Pictures are corrupted when saving

I found an anomaly during tests with this particular device, the details are below:
Hardware: samsung,SM-A326B (Smartphone Samsung A32)
OS: Android 12
ONE UI: 4.1
Google Play: 01/may/22
Patch level: 01/june/22
These are the specs of one device that works properly, the only differences that I see are related to different version of the patch level.
Hardware: samsung,SM-A515F (Smartphone Samsung A51)
OS: Android 12
ONE UI: 4.1
Google Play: 01/may/22
Patch level: 01/may/22
I have implemented a customization of camera2 in my application, this always works except with this device, the specific anomaly is that the images are saved completely white and are corrupted, the image can only be recovered by third party software.
These are the permissions I ask for in the manifest:
<uses-feature android:name="android.hardware.location.gps " />
<uses-feature android:name="android.hardware.location.network" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" tools:ignore="ScopedStorage" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
This is the code that I use to save the images
public void saveCameraImage(Image mImage, File mFile, String mOrientation, Context context) {
ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(mFile);
fileOutputStream.write(bytes);
} catch (IOException e) {
wil.WriteFile("saveImage - Exception: " + e.getMessage(), context);
} finally {
mImage.close();
if (null != fileOutputStream) {
try {
fileOutputStream.close();
} catch (IOException e) {
wil.WriteFile("saveImage - Exception: " + e.getMessage(), context);
} finally {
saveExifData(mFile.getPath(), context);
createThumbs(mOrientation, mFile, context);
}
}
}
}
This is the function that I named "saveExifData"
private void saveExifData(String filepath, Context context) {
try {
if (filepath.endsWith(IMAGE_FORMAT)) {
File file = new File(filepath);
if (file.exists()) {
DbGest dbGest = DbGest.getInstance(context);
String dateTime = dbGest.getTimestampFromFileToSend(filepath, "dateTime", context);
String dateTimeGps = dbGest.getTimestampFromFileToSend(filepath, "gps", context);
String dateTimeDesc = dbGest.getTimestampFromFileToSend(filepath, "dateTimeDesc", context);
ExifInterface exifInterface = new ExifInterface(filepath);
exifInterface.setAttribute(ExifInterface.TAG_COPYRIGHT, "xxxxx ");
exifInterface.setAttribute(ExifInterface.TAG_MODEL, Build.MANUFACTURER + "," + Build.MODEL);
exifInterface.setAttribute(ExifInterface.TAG_SOFTWARE, dbGest.getSetting("appName", context));
exifInterface.setAttribute(ExifInterface.TAG_DATETIME, dateTime);
exifInterface.setAttribute(ExifInterface.TAG_DATETIME_ORIGINAL, dateTime);
exifInterface.setAttribute(ExifInterface.TAG_USER_COMMENT, "Immagine scattata tramite " + dbGest.getSetting("appName", context) + " il " + dateTimeDesc);
CoordinatesData position = DbGest.getInstance(context).getBetterPositionKnown(context);
exifInterface.setAttribute(ExifInterface.TAG_GPS_LATITUDE, String.valueOf(position.getLat()));
exifInterface.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, String.valueOf(position.getLng()));
exifInterface.setAttribute(ExifInterface.TAG_GPS_DATESTAMP, dateTimeGps);
exifInterface.setAttribute(ExifInterface.TAG_GPS_SPEED, String.valueOf(position.getSpeed()));
exifInterface.setLatLong(position.getLat(), position.getLng());
exifInterface.saveAttributes();
}
}
} catch (Exception e) {
wil.WriteFile("saveExifData - Exception: " + e.getMessage(), context);
}
}
So I guess it's not a permission issue, also there are no exceptions, so I don't know how to fix this
After several test and debugging I find the cause of the bug.
The problem it is in the "saveExifData", for some reason this row of code
exifInterface.setAttribute(ExifInterface.TAG_COPYRIGHT, "xxxx");
it is the cause of the problem

Android emulator open failed: ENOENT (No such file or directory)

I need help with permission to save file in Android emulator ... I've had added
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.camera" android:required="true" />
in AndroidManifest.xml
My code for save file:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(imageBitmap);
}
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Img");
myDir.mkdirs();
long n = System.currentTimeMillis();
String fname = "IMG_" + n + ".jpeg";
file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out2 = new FileOutputStream(file);// here fire exception
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out2);
out2.flush();
out2.close();
} catch (Exception e) {
e.printStackTrace();
}
}
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.denis.calculator">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".InfoActivity"></activity><!-- ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information. -->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.camera" android:required="true" />
Any ideas pls?
Solution is downgrade from Nougat to KitKat! thanks for advices
Replace the below lines
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Img");
With
File myDir = new File(Environment.getExternalStorageDirectory(),"Img");
Also remove the below lines from your code
if (file.exists())
file.delete();
Because the way you defining the file name will never gonna have the same file name. So validating the existence of file is irrelevant here.
You also have to ask writing permission with the user if your app is going to be used for Android 6.0 or above. Refer the link given below for details:
https://developer.android.com/training/permissions/requesting.html
You can use the solution defined in the library I've recently created this repository including a demo for Permission.
https://github.com/eeshan-jamal/DroidLibX
I will later make it available through Maven but for now you have to import the droidlibx library module in your project.

MediaMetadataRetriever setDataSource throws IllegalArgumentException

I'm trying to get the size of a remote video using this class and i'm getting IllegalArgumentException if the video is remote.
the video is an mp4 stored in one server...
the video plays correctly if i play it with mediaplayer, but it gives the error if i try to do this:
try {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
Bitmap bmp = null;
retriever.setDataSource(context, uri);
bmp = retriever.getFrameAtTime();
videoHeight = (int) (bmp.getHeight()*((float)getIntWidth()/bmp.getWidth()));
} catch (Exception e) {
e.printStackTrace();
}
the error is thrown in this line:
retriever.setDataSource(context, uri);
and uri contains Uri.parse("http://www.myweb.com/myvideo.mp4");
what is wrong in the code?
12-19 13:38:08.610: W/System.err(13333): java.lang.IllegalArgumentException
12-19 13:38:08.611: W/System.err(13333): at android.media.MediaMetadataRetriever.setDataSource(MediaMetadataRetriever.java:175)
Maybe you are running into this bug. If so try:
try {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
Bitmap bmp = null;
retriever.setDataSource("http://www.myweb.com/myvideo.mp4", new HashMap<String, String>());
bmp = retriever.getFrameAtTime();
videoHeight = (int) (bmp.getHeight()*((float)getIntWidth()/bmp.getWidth()));
} catch (Exception e) {
e.printStackTrace();
}
If that doesn't work you can always try FFmpegMediaMetadataRetriever:
FFmpegMediaMetadataRetriever retriever = new FFmpegMediaMetadataRetriever();
try {
Bitmap bmp = null;
retriever.setDataSource("http://www.myweb.com/myvideo.mp4"));
bmp = retriever.getFrameAtTime();
videoHeight = (int) (bmp.getHeight()*((float)getIntWidth()/bmp.getWidth()));
} catch (Exception e) {
e.printStackTrace();
}
retriever.release();
I was getting the same error, I am using android 10.
I solved just putting android:requestLegacyExternalStorage="true" in Manifest inside application.
See here
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:requestLegacyExternalStorage="true"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
In my case, I was creating a simple metadata extraction test app, so I copied a file to my phone using adb, like so:
adb push 350950598.mp4 /sdcard/Movies
but I forgot to add the read external storage directory permission in the app manifest.
Specifically:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="my.cool.package.name">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
...
</manifest>
Adding those permissions fixed it for me, even for the simple file string call:
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(movie.getPath());
And of course, if you're targeting API 23+ marshmallow then you'll have to dynamically ask for those permissions, as well.
try {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
Bitmap bmp = null;
retriever.setDataSource(uri.toString(), new HashMap<String, String>());
bmp = retriever.getFrameAtTime();
videoHeight = (int) (bmp.getHeight()*((float)getIntWidth()/bmp.getWidth()));
} catch (Exception e) {
e.printStackTrace();
}
You need to give runtime permissions if you are using Android Marshmallow or later.
Android Manifest File:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="my.cool.package.name">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
...
Then add code for runtime permissions in your activity. After that, run your application and it should work.
if you are uses android 10 or above one then you need to mention requestLegacyExternalStorage to true.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:requestLegacyExternalStorage="true"
android:supportsRtl="true"
android:theme="#style/AppTheme">
Note : if by doing this still you're facing the same issue then you need to reinstall the app. :)

Copy file to external sdcard android

I cannot copy a file to the external sdcard. Does not show up any error, in-fact shows success, but the file is not on the sd card. Code is as follows:
window.resolveLocalFileSystemURI(fileURI, step1,fail);
function step1(tmp_file)
{
file = tmp_file;
window.resolveLocalFileSystemURI("file:///mnt/extsd", step2,fail); //resolve destinaion
}
function step2(destination)
{
file.moveTo(destination,"example.jpg",move_success, move_fail);
}
So on the end it calls move_success.
NOTE: IT WORKS IF I CHANGE PATH FROM 'file:///mnt/extsd' to the internal sdcard path 'file:///mnt/sdcard'
Permissions in manifest
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
You should build your path, not define it as default, cause not in all devices the sdcard is called "sdcard", for example, i have a chinnese tablet, and this has 2 sdcard slots, so i have to use the path "sdcard2" you can do it:
File sdcard = Environment.getExternalStorageDirectory();
String path = "file://"+sdcard.getAbsolutePath();
Then you can use the variable
window.resolveLocalFileSystemURI(path, step2,fail); //resolve destinaio
Or, you can use this method to copy a file:
public void copy(File src, File dst) throws IOException {
try {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (IOException io) {
Toast.makeText(this, "Error: " + io, Toast.LENGTH_LONG).show();
}
}
You can copy the file, next delete it, as a fast move.
Or as other alternative, you can use the property renameTo() of the file,
For example:
File sdcard = Environment.getExternalStorageDirectory();
File example= new File(sdcard.getAbsolutePath()+"/example.txt");
File newpath= new File(sdcard.getAbsolutePath()+"/examplefolder/example.txt");
example.renameTo(newpath);//this will move the file to the new path

Categories

Resources