FileProvider:- Setting up file sharing
I know that change the file policy in android nougat.
The wanted app that file share to other apps generate the uri by FileProvider.
The uri format is content://com.example.myapp.fileprovider/myimages/default_image.jpg
.
I want know that how can I get filepath from the uri that generate by FileProvider.getUriForFile()
.
because the my app is need to know the physical filepath in order to save, load, readinfo, etc.
is it possible
[In short]
content://com.example.myapp.fileprovider/myimages/default_image.jpg
FileProvider.getUriForFile
.getContentResolver().openFileDescriptor()
.
but I wnat to know the filepath.You cannot get a "file path" for a Uri, for the simple reason that there is no requirement that a Uri point to a file. Use ContentResolver and methods like openInputStream() to access the content represented by the Uri.
To share a file with another app using a content URI, your app has to generate the content URI. To generate the content URI, create a new File for the file, then pass the File to getUriForFile(). You can send the content URI returned by getUriForFile() to another app in an Intent. The client app that receives the content URI can open the file and access its contents by calling ContentResolver.openFileDescriptor to get a ParcelFileDescriptor. Source: Android developers
// Use Below Method Working fine for Android N.
private static String getFilePathForN(Uri uri, Context context) {
Uri returnUri = uri;
Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
/*
* Get the column indexes of the data in the Cursor,
* * move to the first row in the Cursor, get the data,
* * and display it.
* */
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
String name = (returnCursor.getString(nameIndex));
String size = (Long.toString(returnCursor.getLong(sizeIndex)));
File file = new File(context.getFilesDir(), name);
try {
InputStream inputStream = context.getContentResolver().openInputStream(uri);
FileOutputStream outputStream = new FileOutputStream(file);
int read = 0;
int maxBufferSize = 1 * 1024 * 1024;
int bytesAvailable = inputStream.available();
//int bufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
final byte[] buffers = new byte[bufferSize];
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
Log.e("File Size", "Size " + file.length());
inputStream.close();
outputStream.close();
Log.e("File Path", "Path " + file.getPath());
} catch (Exception e) {
Log.e("Exception", e.getMessage());
}
return file.getPath();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With