How to open a file in Android (for example, an image) by means of the system. That is, to open the file in the application that is provided for this type.

Updated.

In order for the system to understand which applications it can open the file, you must explicitly specify the mime-type. The library has a special class for working with mime-types: android.webkit.MimeTypeMap .

In order to get the mime-type, we first find out the file extension.

 String extension = MimeTypeMap.getFileExtensionFromUrl(url); String mType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); 

But such code will not work, since

  • The getFileExtensionFromUrl method returns an extension true, only if the file name contains only Latin characters (no spaces, no Cyrillic, etc.).
  • The getMimeTypeFromExtension method works correctly only if the extension is in lower case (so add toLowerCase ).

Further. If you configure intent like this

 intent.setData(Uri.fromFile(file)); intent.setType(mType); 

then only type will be set, and data will be null . If the lines are reversed, then, on the contrary, type == null . Those. either one or the other. It only worked like this:

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

(tested on a device from Motorola)

    2 answers 2

    Opening a file is quite simple:

     Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("file:///mnt/sdcard/file.xls")); startActivity(intent); 

    The absolute path to the required file is passed to Uri.parse. Instead of Uri.parse, you can specify a ready Uri, if you have it in the application.

    If only one application can open the specified file, the file will be opened immediately; if several, the dialog will open to select the required application. If this type of file cannot be opened by any application in the system, a standard system message about this will be displayed.

    • @Dr Zoidberg; For some reason, without explicit indication, mime-type did not work for me. - angry

    You need to add a specific intent-filter to the manifest, but the application must be ready to catch this filter. The filter can be your own. Here is the dock - tyts And an example from it:

     <intent-filter . . . > <data android:mimeType="video/mpeg" android:scheme="http" . . . /> <data android:mimeType="audio/mpeg" android:scheme="http" . . . /> . . . </intent-filter> 

    It will be useful to get acquainted with an example: tyts

    If I understand your question correctly.

    • ) question: as in an adroid ....? )) answer: developer.android.com - Gorets
    • The author asked how from his application to open any file in the application associated with this type of files. And you tell him how to associate your application with a specific file type. - Dr Zoidberg
    • one
      Questions need to be asked more precisely, IMHO. I do not own telepathy. The second part of the author's question was confused, it is superfluous in this case. - DroidAlex