如何在Android中的API 29中将图像保存在图库中? [英] How to save image in gallery in API 29 in android?

查看:78
本文介绍了如何在Android中的API 29中将图像保存在图库中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从API 29开始,不推荐使用 Environment.getExternalStorageDirectory() Intent.ACTION_MEDIA_SCANNER_SCAN_FILE .

From API 29 Environment.getExternalStorageDirectory() and Intent.ACTION_MEDIA_SCANNER_SCAN_FILE are deprecated.

我使用以下代码将图像文件保存到内部存储中的特定文件夹中:

I used the following code to save an image file to a specific folder in internal storage :

  private fun saveFile(applicationContext: Context, file: File){
    val folder  = "/customFolder"
    try {
        val destFile = File("${Environment.getExternalStorageDirectory()}${folder}/${file.name}")
        FileUtils.copyFile(file,destFile) 

        val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
        val contentUri = Uri.fromFile(file)!!
        mediaScanIntent.data = contentUri
        applicationContext.sendBroadcast(mediaScanIntent)

    } catch (ex: IllegalArgumentException) {
    } catch (ex: RuntimeException) {
    }
}

FileUtils.copyFile(File srcFile,File destFile)的引用链接-在更新为API 29之后,以上代码无效.如何为API 29修改 Environment.getExternalStorageDirectory() Intent.ACTION_MEDIA_SCANNER_SCAN_FILE ?

After updating to API 29 above code doesn't work. How to modify Environment.getExternalStorageDirectory() and Intent.ACTION_MEDIA_SCANNER_SCAN_FILE for API 29 ?

推荐答案

这将起作用,它将文件存储在应用程序指定的文件夹中,您也可以使用MediaStorage来将img存储在图库中,新功能现在是getFilesDir()getExternalFilesDir(),getCacheDir(),getExternalCacheDir(),

This will work, This will store your file in app specified folder , you can user MediaStorage as well to store img in gallery , the new functions are now getFilesDir() getExternalFilesDir(), getCacheDir(),getExternalCacheDir(),

String path = ApplicationContext.getExternalFilesDir(null)+Foldername+filename;
File file = new File(path);
file.getParentFile().mkdir();
 try {
            OutputStream fileOutputStream = new FileOutputStream(file);
            savedBitmap.compress(CompressFormat.JPEG, 100, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (IOException e2) {
            e2.printStackTrace();
        }

这篇关于如何在Android中的API 29中将图像保存在图库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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