直接使用 Uri.fromFile(file) 搭配 ACTION_VIEW 且 setType("image/*"),在 Android 7.0+ 會因 file:// Uri 被禁止跨應用傳遞而拋出 ActivityNotFoundException 或 FileUriExposedException。
File imageFile = new File(filename);
Uri contentUri = FileProvider.getUriForFile(
this, getPackageName() + ".fileprovider", imageFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(contentUri, "image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "無可用圖片檢視器", Toast.LENGTH_SHORT).show();
}
AndroidManifest.xml 宣告 Provider:<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
res/xml/file_paths.xml 定義可分享路徑:<paths>
<files-path name="my_images" path="images/"/>
<external-files-path name="my_images_ext" path="Pictures/"/>
</paths>
將圖片插入 MediaStore.Images.Media,取得 content:// Uri,系統相簿自動掃描可見。
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DISPLAY_NAME, "photo.jpg");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
// 寫入檔案流...
// 最後開啟
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setDataAndType(uri, "image/*");
startActivity(intent);