Skip to content

Instantly share code, notes, and snippets.

@xyznaveen
Created December 17, 2018 06:03
Show Gist options
  • Save xyznaveen/6ec3f33199a1bba73a59e61488df6a8a to your computer and use it in GitHub Desktop.
Save xyznaveen/6ec3f33199a1bba73a59e61488df6a8a to your computer and use it in GitHub Desktop.
private void showOpenWith(File file) {
if (getContext() == null) {
return;
}
String extension = getFileExtension(file);
Uri uri = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(getContext(), "dynamic.school.fileprovider", file);
} else {
uri = Uri.fromFile(file);
}
Log.i("BQ7CH72", "File uri :: " + uri);
try {
MimeTypeMap mime = MimeTypeMap.getSingleton();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(uri, mime.getMimeTypeFromExtension(extension));
startActivityForResult(intent, ACTIVITY_VIEW_ATTACHMENT);
} catch (ActivityNotFoundException e) {
Toast.makeText(getContext(), "This file cannot be viewed on this device." +
" Application not found for opening this type of file.", Toast.LENGTH_LONG).show();
}
}
private String getFileExtension(File file) {
String[] files = file.getAbsolutePath().split("\\\\");
files = files[files.length - 1].split("\\.");
return files[files.length - 1];
}
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="my.domain.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="my_images"
path="Android/data/dynamic.school/files/Pictures" />
<external-path
name="external_files"
path="/" />
<external-files-path
name="external_files"
path="/" />
<root-path
name="sdcard1"
path="/" />
<cache-path
name="cache"
path="/" />
<files-path
name="files"
path="/" />
</paths>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment