Android - How do I open a file in another app using an Intent?
I am trying to open a file using another application, i.e. opening .jpg with Gallery, .pdf with Acrobat, etc.
The problem I am facing is when I try to open a file in the application, it only opens the selected application and does not open the file in the application. I tried after Android to open a PDF file via an Intent , but I am missing something.
public String get_mime_type(String url) {
String ext = MimeTypeMap.getFileExtensionFromUrl(url);
String mime = null;
if (ext != null) {
mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
}
return mime;
}
public void open_file(String filename) {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), filename);
// Get URI and MIME type of file
Uri uri = Uri.fromFile(file).normalizeScheme();
String mime = get_mime_type(uri.toString());
// Open file with user selected app
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
intent.setType(mime);
context.startActivity(Intent.createChooser(intent, "Open file with"));
}
As far as I can tell, it returns the correct URI and MIME type:
URI: file:///storage/emulated/0/Download/Katamari-ringtone-985279.mp3
MIME: audio/mpeg
+4
source to share
2 answers
Post your changes here in case it can help someone else. As a result, I changed the download location to an internal folder and added a content provider.
public void open_file(String filename) {
File path = new File(getFilesDir(), "dl");
File file = new File(path, filename);
// Get URI and MIME type of file
Uri uri = FileProvider.getUriForFile(this, App.PACKAGE_NAME + ".fileprovider", file);
String mime = getContentResolver().getType(uri);
// Open file with user selected app
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(uri, mime);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
}
+6
source to share
I used this piece of code and it worked fine on Android 6 and below, not tested on a higher version
public void openFile(final String fileName){
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File(android.os.Environment.getExternalStorageDirectory()
.getAbsolutePath()+ File.separator+"/Folder/"+fileName));
intent.setDataAndType(uri, "audio/mpeg");
startActivity(intent);
}
0
source to share