Reputation: 6027
I have an app in which user can upload file with any exetention(.png,.mp3,.txt,.pdf,.bmp,.apk,...etc)
In a nutshell-->** the file with any exe..!**
These files r displayed in list-view.
When user 'Tap' or 'click' on item from list-view intent will be called (android.content.Intent.ACTION_VIEW
) and it should be open the respective application which installed in device.
For Example
If User Click on nature.png then intent will be called and suggest the applications like Gallery,PS Touch..etc(As shown in screen shot1)
If User Click on book.pdf then intent will be called and suggest the applications like MuPdf,Polaris Office,apv..etc(As shown in screen shot2)
For .txt,.pdf,.png,.jpg-- I have solved the problem by set mime type intent.setDataAndType(Uri.fromFile(file), mime);
and also for URL
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(https://www.google.co.in/));
It is working perfectly but for rest of the file extension i m still confused- What to do? and how to do?
I have already dig around,but couldn't get satisfactorily answer..!
My Questions:
Upvotes: 12
Views: 22602
Reputation: 89
public void openFile() {
try {
File file = new File(G.DIR_APP + fileName);
fileExtension = fileName.substring(fileName.lastIndexOf("."));
Uri path = Uri.fromFile(file);
Intent fileIntent = new Intent(Intent.ACTION_VIEW);
fileIntent.setDataAndType(path, "application/" + fileExtension);
startActivity(fileIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(G.currentActivity, "Cant Find Your File", Toast.LENGTH_LONG).show();
}
}
Upvotes: 0
Reputation: 2097
Pointing to the first part of your question:
try
{
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
catch (ActivityNotFoundException e)
{
//tel the user to install viewer to perform this action
}
There's no need to specify the type. It will get it from the data URI.
Upvotes: 2
Reputation: 40218
The following code will work for every file type:
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), fileMimeType);
startActivity(intent);
} catch (ActivityNotFoundException e) {
// no Activity to handle this kind of files
}
Of course, there should be an Activity
in the system that knows how to handle the file of a certain type. Hope this helps.
Upvotes: 10