天使漫步IT工作室天使漫步IT工作室

如何让 Android 保存图片显示到相册(解决无法显示和适配7.0)


Warning: count(): Parameter must be an array or an object that implements Countable in /www/wwwroot/u11u.com/usr/themes/wq/functions.php on line 110

Warning: count(): Parameter must be an array or an object that implements Countable in /www/wwwroot/u11u.com/usr/themes/wq/functions.php on line 116

一般android应用中会有需求要下载原图,那么怎么让下载完的图片显示在相册中?一般的步骤:

    1. 下载图片到本地SD卡。
    1. 图片路径插入到Media数据表。
    1. 发送广播触发系统扫描文件(将文件的缩略图更新到相册中)。

示例代码如下:

try {
        MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), null);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    // 最后通知图库更新
    Uri contentUri;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        contentUri = FileProvider.getUriForFile(this, "com.xxx.xx.fileprovider", file);
    } else {
        contentUri = Uri.parse("file://" + file.getAbsolutePath());
    }
    this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, contentUri));

以上代码在发送广播之前,分别针对不同的版本使用不同的api生成uri(适配android7.0版本)

网上有教程说可以使用ACTION_MEDIA_MOUNTED广播来触发系统扫描文件,但是根据android-KITKAT(19)版本以后的要求,只有系统才能使用此广播。如果在高于19版本的android上使用,会触发没有权限的bug。那么如何兼容KITKAT以前的版本要求?

兼容步骤如下:

<protected-broadcast android:name="android.intent.action.MEDIA_MOUNTED" />

代码示例:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
   final Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
   final Uri contentUri = Uri.fromFile(outputFile); 
   scanIntent.setData(contentUri);
   sendBroadcast(scanIntent);
} else {
   final Intent intent = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()));
   sendBroadcast(intent);
}

综合上面,我们可以在大于KITKAT(19)版本的逻辑分支里面又进行更细化的适配处理。

参考文章:

本站原创,欢迎转载,转载敬请标明出处:天使漫步IT工作室 » 如何让 Android 保存图片显示到相册(解决无法显示和适配7.0)
添加新评论


Warning: Use of undefined constant php - assumed 'php' (this will throw an Error in a future version of PHP) in /www/wwwroot/u11u.com/usr/themes/wq/comments.php on line 38