1.make sure you get the storage permission.
2.add sth. in your manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...
<application
>
...
<provider
android:name="android.support.v4.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>
</manifest>
3.create 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>
4.test in a Activity :
onCreate(){
String path = getExternalCacheDir().getAbsolutePath();
openAssignFolder(path);
}
private void openAssignFolder(String path) {
File file = new File(path);
if (null == file || !file.exists()) {
return;
}
try {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.fromFile(file);
if (Build.VERSION.SDK_INT > 19) { // 7.0+
uri = FileProvider.getUriForFile(getApplicationContext(),
getApplicationContext().getPackageName() + ".provider", file);
}
intent.setDataAndType(uri, "file/*");
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
If `targetSdkVersion` is higher than **24**, then [FileProvider][1] is used to grant access.
Create an xml file(Path: res\xml\) **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>
<br>
Add a **Provider** in **[AndroidManifest.xml][2]**
<provider
android:name="android.support.v4.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>
If you are using **androidx**, the FileProvider path should be:
android:name="androidx.core.content.FileProvider"
and **replace**
Uri uri = Uri.fromFile(fileImagePath);
to
Uri uri = FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID + ".provider",fileImagePath);
**Edit:** While you're including the URI with an `Intent` make sure to add below line:
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
and you are good to go. Hope it helps.
[1]: https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjiyKWypuDVAhVIso8KHcA2BvIQFgglMAA&url=https%3A%2F%2Fdeveloper.android.com%2Freference%2Fandroid%2Fsupport%2Fv4%2Fcontent%2FFileProvider.html&usg=AFQjCNEBbyss3j2b0k_XQncN1I9vLhrlGQ
[2]: https://developer.android.com/guide/topics/manifest/manifest-intro.html