Reputation: 710
I want to open a given file using installed apps in Android. How can I do that?
I am using the following code from Google but it always returns "No app to open this file"
. But if I open that file in other file managers, I see different options to open that file. Code:
public void open(View v) {
String name = ((TextView) v).getText().toString();
File f = new File(path + name);
if (f.isDirectory()) {
showFiles(f);
} else if (f.isFile()) {
Intent openFileIntent = new Intent(Intent.ACTION_VIEW);
openFileIntent.setData(Uri.fromFile(f));
if (openFileIntent.resolveActivity(getPackageManager()) != null) {
startActivity(openFileIntent);
} else {
Toast.makeText(this, "No app to open this file.",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Selected item is not a file.",
Toast.LENGTH_SHORT).show();
}
}
Upvotes: 1
Views: 101
Reputation: 8742
You should specify a MIME type so Android knows which app is capable of opening / viewing the file. This should work for you:
public void open(View v) {
String name = ((TextView) v).getText().toString();
File f = new File(path + name);
if (f.isDirectory()) {
showFiles(f);
} else if (f.isFile()) {
Intent openFileIntent = new Intent(Intent.ACTION_VIEW);
openFileIntent.setDataAndType(Uri.fromFile(f), getMimeTypeFromFile(f));
if (openFileIntent.resolveActivity(getPackageManager()) != null) {
startActivity(openFileIntent);
} else {
Toast.makeText(this, "No app to open this file.",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Selected item is not a file.",
Toast.LENGTH_SHORT).show();
}
}
private String getMimeTypeFromFile(File f){
Uri fileUri = Uri.fromFile(f);
String fileExtension
= MimeTypeMap.getFileExtensionFromUrl(fileUri.toString());
String fileType
= MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);
if (fileType == null)
fileType = "*/*";
return fileType;
}
Upvotes: 1