在 Android 默认图库图像查看器中使用 URI 打开图像

问题描述 投票:0回答:14

我已经提取了图像 uri,现在我想使用 Android 的默认图像查看器打开图像。或者更好的是,用户可以选择使用什么程序来打开图像。如果您尝试打开文件,可以使用文件资源管理器之类的工具。

android android-image
14个回答
181
投票

接受的答案对我不起作用,

什么有效:

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + "/sdcard/test.jpg"), "image/*");
startActivity(intent);

42
投票

如果您的应用程序面向 Android N (7.0) 及更高版本,则不应使用上面的答案(“Uri.fromFile”方法),因为它不适合您。

相反,您应该使用 ContentProvider。

例如,如果您的图像文件位于外部文件夹中,您可以使用它(类似于我制作的代码here):

File file = ...;
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(VERSION.SDK_INT >= VERSION_CODES.N ? FileProvider.getUriForFile(this,getPackageName() + ".provider", file) : Uri.fromFile(file), "image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);

清单:

<provider
    android:name="androidx.core.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>

res/xml/provider_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <!--<external-path name="external_files" path="."/>-->
    <external-path
        name="files_root"
        path="Android/data/${applicationId}"/>
    <external-path
        name="external_storage_root"
        path="."/>
</paths>

如果您的图像位于应用程序的私有路径中,您应该创建自己的 ContentProvider,因为我在链接上创建了“OpenFileProvider”。


34
投票

问自己,也回答自己:

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("content://media/external/images/media/16"))); /** replace with your own uri */

它还会询问使用什么程序来查看文件。


22
投票

尝试使用它:

Uri uri =  Uri.fromFile(entry);
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
String mime = "*/*";
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
if (mimeTypeMap.hasExtension(
    mimeTypeMap.getFileExtensionFromUrl(uri.toString())))
    mime = mimeTypeMap.getMimeTypeFromExtension(
        mimeTypeMap.getFileExtensionFromUrl(uri.toString()));
intent.setDataAndType(uri,mime);
startActivity(intent);

18
投票

基于 Vikas 回答,但略有修改:Uri 通过参数接收:

private void showPhoto(Uri photoUri){
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setDataAndType(photoUri, "image/*");
    startActivity(intent);
}

12
投票

如果您使用 Android N 及以下版本,这件事可能会有所帮助

 File file=new File(Environment.getExternalStorageDirectory()+"/directoryname/"+filename);
        Uri path= FileProvider.getUriForFile(MainActivity.this,BuildConfig.APPLICATION_ID + ".provider",file);

        Intent intent=new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(path,"image/*");
        intent.setFlags(FLAG_GRANT_READ_URI_PERMISSION | FLAG_GRANT_WRITE_URI_PERMISSION); //must for reading data from directory

6
投票

对这个问题有一个更干净、更安全的答案(你真的不应该对字符串进行硬编码):

public void openInGallery(String imageId) {
  Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI.buildUpon().appendPath(imageId).build();
  Intent intent = new Intent(Intent.ACTION_VIEW, uri);
  startActivity(intent);
}

您所要做的就是将图像 ID 附加到 EXTERNAL_CONTENT_URI 的路径末尾。然后使用 View 操作和 Uri 启动 Intent。

图像 ID 来自查询内容解析器。


4
投票

以上所有答案均未打开图像。当我第二次尝试打开它时,显示图库而不是图像。

我从各种SO答案的混合中得到了解决方案..

Intent galleryIntent = new Intent(Intent.ACTION_VIEW, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setDataAndType(Uri.fromFile(mImsgeFileName), "image/*");
galleryIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(galleryIntent);

这个只对我有用..


4
投票

使用

Intent.ACTION_VIEW
显示文件的问题是,如果您通过
Uri
解析路径。并非在所有情况下都有效。要解决该问题,您需要使用:

Uri.fromFile(new File(filePath));

代替:

Uri.parse(filePath);

编辑

这是我的完整代码:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(mediaFile.filePath)), mediaFile.getExtension());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

信息

MediaFile
是我的域类,用于将数据库中的文件包装在对象中。
MediaFile.getExtension()
返回
String
,其中
Mimetype
表示文件扩展名。示例:
"image/png"


附加代码:显示任何文件(扩展名)所需

import android.webkit.MimeTypeMap;

public String getExtension () {
    MimeTypeMap myMime = MimeTypeMap.getSingleton();
    return myMime.getMimeTypeFromExtension(MediaFile.fileExtension(filePath));
}

public static String fileExtension(String path) {
    if (path.indexOf("?") > -1) {
        path = path.substring(0, path.indexOf("?"));
    }
    if (path.lastIndexOf(".") == -1) {
        return null;
    } else {
        String ext = path.substring(path.lastIndexOf(".") + 1);
        if (ext.indexOf("%") > -1) {
            ext = ext.substring(0, ext.indexOf("%"));
        }
        if (ext.indexOf("/") > -1) {
            ext = ext.substring(0, ext.indexOf("/"));
        }
        return ext.toLowerCase();
    }
}

如果您需要更多代码,请告诉我。


3
投票

我用这个,它对我有用

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), 1);

2
投票

我使用文件提供程序的解决方案

    private void viewGallery(File file) {

 Uri mImageCaptureUri = FileProvider.getUriForFile(
  mContext,
  mContext.getApplicationContext()
  .getPackageName() + ".provider", file);

 Intent view = new Intent();
 view.setAction(Intent.ACTION_VIEW);
 view.setData(mImageCaptureUri);
 List < ResolveInfo > resInfoList =
  mContext.getPackageManager()
  .queryIntentActivities(view, PackageManager.MATCH_DEFAULT_ONLY);
 for (ResolveInfo resolveInfo: resInfoList) {
  String packageName = resolveInfo.activityInfo.packageName;
  mContext.grantUriPermission(packageName, mImageCaptureUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
 }
 view.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
 Intent intent = new Intent();
 intent.setAction(Intent.ACTION_VIEW);
 intent.setDataAndType(mImageCaptureUri, "image/*");
 mContext.startActivity(intent);
}

0
投票

几乎没有有机会使用照片或图库应用程序(可能存在),但您可以尝试内容查看器。

请查看类似问题的另一个答案这里


0
投票

我的解决方案

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath()+"/your_app_folder/"+"your_picture_saved_name"+".png")), "image/*");
context.startActivity(intent);

0
投票

uri必须是内容uri而不是文件uri, 您可以通过 FileProvider 获取 contentUri 作为

Uri contentUri = FileProvider.getUriForFile(getContext(),"com.github.myApp",curFile);

不要忘记在 Manifest 文件中添加提供程序。

<provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="com.github.myApp"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths" />
</provider>
© www.soinside.com 2019 - 2024. All rights reserved.