Open files in android using the default application
I’m making a file explorer in android. So I want to get a suggestion of an application that can open it when clicking on any file outside of the directory, and a dailog that shows if there is no application. I tried some solutions but nothing worked, so, for now, I’m just showing that the file isn’t a directory in the toast
Part of the code is as follows:
protected void onListItemClick(ListView l, View v, int position, long id) {
String filename = (String) getListAdapter().getItem(position);
if (path.endsWith(File.separator)) {
filename = path + filename;
} else {
filename = path + File.separator + filename;
}
if (new File(filename).isDirectory()) {
Intent intent = new Intent(this, ListFileActivity.class);
intent.putExtra("path", filename);
startActivity(intent);
} else {
Toast.makeText(this, filename + " is not a directory", Toast.LENGTH_LONG).show();
}
}
Solution
Android has some built-in Intent Action Type This can help you open or view a specific file, but for this you need to know the type of file you want to work with.
Assume that you have a file type that can be categorized by using document types
ACTION_OPEN_DOCUMENT
has a specific MIME_TYPE
(Android 4.4 or later).
Or if you are going to process some media files (audio/video).
You can use it
ACTION_VIEW
To identify the MIME_TYPE
of a specific file, you can use functions
guessContentTypeFromName (string url).
Link
or getMimeTypeFromExtension <
a href="http://developer.android.com/reference/android/webkit/MimeTypeMap.html#getMimeTypeFromExtension( java.lang.String)" rel="noreferrer noopener nofollow">Link