Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically open Intent Chooser for the file Android

I want to open a file in android. What i want to do is if the file is of type Image then i want to open Intent Chooser which contains applications that can view the image, and if it is of video type, then open Intent Chooser with applications that can view videos. How can i achieve this?

like image 822
Unnati Avatar asked Apr 18 '14 06:04

Unnati


People also ask

What is startActivity in android?

Starting activities or services. To start an activity, use the method startActivity(intent) . This method is defined on the Context object which Activity extends. The following code demonstrates how you can start another activity via an intent.

What is the use of intent createChooser () method?

createChooser(intent, title); // Try to invoke the intent. // Define what your app should do if no activity can handle the intent. This displays a dialog with a list of apps that respond to the intent passed to the createChooser() method and uses the supplied text as the dialog title.

What is Intentfilter?

An intent filter declares the capabilities of its parent component — what an activity or service can do and what types of broadcasts a receiver can handle. It opens the component to receiving intents of the advertised type, while filtering out those that are not meaningful for the component.

What is intent setType in android?

setType(String mimeType) input param is represent the MIME type data that u want to get in return from firing intent(here myIntent instance). by using one of following MIME type you can force user to pick option which you desire. Please take a Note here, All MIME types in android are in lowercase.


2 Answers

I have found a solution. I am pasting it here so it may help other users.

    Intent intent = new Intent();
    intent.setAction(android.content.Intent.ACTION_VIEW);
    File file = new File(path);

    MimeTypeMap mime = MimeTypeMap.getSingleton();
    String ext = file.getName().substring(file.getName().lastIndexOf(".") + 1);
    String type = mime.getMimeTypeFromExtension(ext);

    intent.setDataAndType(Uri.fromFile(file), type);

    context.startActivity(intent);
like image 110
Unnati Avatar answered Sep 28 '22 08:09

Unnati


You should decide and know whether the file is video or image. You may do it by looking at the extension of the files.

After that you can open videos like this:

Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.parse(result), "video/*");
startActivity(intent);

and images like this:

Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.parse(result), "image/*");
startActivity(intent);

Android system will open the Intent Chooser automatically.

like image 29
tasomaniac Avatar answered Sep 28 '22 09:09

tasomaniac