使图像文件在 Lollipop 的 Android 图库中可见 [英] Make image File visible in Android Gallery on Lollipop

查看:27
本文介绍了使图像文件在 Lollipop 的 Android 图库中可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使在应用程序中拍摄的一些照片在图库中可见(以便它们可以在应用程序外部共享和查看),但我想将图像本身保留在应用程序的数据目录中因此,当应用被删除时,它们会被删除(因此它们存储在 "{sdcard}/Android/data/{appID}/Pictures/{subfolder}/")中.

I am trying to make some pictures that are taken in the app visible in the Gallery (so they can be shared and looked at outside of the app), but I want to keep the images themselves inside the data directory of the app so when the app is deleted they get removed (so they are stored in "{sdcard}/Android/data/{appID}/Pictures/{subfolder}/").

我查看了很多答案,对于旧版本的 Android,以下两种解决方案都有效,但它们似乎不适用于 Lollipop:

I have looked at a lot of answers and for older versions of Android both of the following solutions work, but they don't seem to work in Lollipop:

MediaScannerConnection.scanFile(this,
    new String[]{file.toString()}, new String[] { "image/jpeg" },
    new MediaScannerConnection.OnScanCompletedListener() {
        public void onScanCompleted(String path, Uri uri) {
            Log.i("ExternalStorage", "Scanned " + path + ":");
            Log.i("ExternalStorage", "-> uri=" + uri);
        }
    });

Uri contentUri = Uri.fromFile(file);
Intent mediaScanIntent = new 
    Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,contentUri);
sendBroadcast(mediaScanIntent);

我已经在 Nexus 4 (Android 5.0.1) 和 Nexus 6 (Android 5.1) 上测试过,但它不起作用.在 Nexus 7 (Android 4.2.2) 中它确实有效.所有 3 台设备在 {sdcard}/Android/data/ 文件夹中都有一个.onmedia"文件,因此正常的媒体扫描应该不会拾取它们...

I have tested this in a Nexus 4 (Android 5.0.1) and a Nexus 6 (Android 5.1) and it doesn't work. In a Nexus 7 (Android 4.2.2) it does work. All 3 devices have a ".onmedia" file in the {sdcard}/Android/data/ folder, so no normal media scan should pick them up...

有没有人知道解决方法可以让它在所有设备/Android 版本上运行?这应该是因为 noMedia 文件首先不起作用吗? Lollipop 是唯一正确执行此操作的版本吗?

Does anyone know a work around to get this to work on all devices/Android versions? Should this because of the noMedia file not work in the first place and is Lollipop the only version that does this correctly?

请注意,即使重启手机(这也应该触发重新扫描文件)也不起作用.并且有充分的理由,因为文件位于.nomedia"目录的子文件夹中......所以我认为任何包含 MEDIA_MOUNTED 广播的解决方案都是无用的.

推荐答案

试试下面的代码.它在棒棒糖中对我有用,希望对你也有用

Try below code. It working for me in Lollipop, Hope working for you as well

ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA,"file path");
values.put(MediaStore.Images.Media.MIME_TYPE,"image/jpeg");
mContext.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);

不要忘记将此添加到您的清单中(尽管在 Lollipop 中不再需要它):

Don't forget to add this to your manifest (although in Lollipop it should no longer be necessary):

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

这篇关于使图像文件在 Lollipop 的 Android 图库中可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆