How to display image with intent.ACTION_VIEW

朱郁亭 picture 朱郁亭 · Feb 17, 2017 · Viewed 9.1k times · Source

My grammar can run at android 5.1 but is not working at android 7.1....

File file = new File(Environment.getExternalStorageDirectory(), "Pictures/1481853170451.jpg");
Toast.makeText(MainActivity.this, file.getPath(), Toast.LENGTH_LONG).show();
Uri path = Uri.fromFile(file);

if (file.exists()) {
  Intent intent = new Intent();
  intent.setAction(android.content.Intent.ACTION_VIEW);
  intent.setDataAndType(path, "image/*");
  intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {                       
  this.startActivity(intent);
} catch (ActivityNotFoundException e) {
}

Can any one tell me possible answer. Thank you in advance....

Answer

Bruce picture Bruce · Apr 19, 2018

Here are the steps

1) In AndroidManifest.xml add the following provider inside application tag

 <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>

2) Create provider_paths.xml in res/xml folder with the following sample content

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="internal_files" path="DATA/TITLE/"/>
</paths>

3) Create the image file in Activity with path as shown below

  context.getFilesDir() + File.separator + "DATA" + File.separator + "TITLE"+ File.separator + "sample_image_file"

4) open the image file using the following code

 Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            Uri photoURI = FileProvider.getUriForFile(context,
                    BuildConfig.APPLICATION_ID + ".provider",
                    new File(context.getFilesDir() + File.separator + "DATA" + File.separator + "TITLE"+ File.separator + "sample_image_file"));
            intent.setDataAndType(photoURI,"image/*");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            context.startActivity(Intent.createChooser(intent, "View using"));