【问题标题】:Save picture in app-reserved memory in Android 11在 Android 11 中将图片保存在应用程序保留的内存中
【发布时间】:2020-12-02 13:17:33
【问题描述】:

Android 11 强制要求 scoped storage。在这种情况下,我希望我的应用程序拍摄一张照片并将其保存到某种 应用程序保留的内存中,以便从图库中删除该图片时仍然可用。我正在使用以下方法

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri outputFileUri = Uri.fromFile(newFile);
if (android.os.Build.VERSION.SDK_INT >= 24) {
   outputFileUri = FileProvider.getUriForFile(myActivity, BuildConfig.APPLICATION_ID + ".provider", newFile);
   cameraIntent.setFlags(FLAG_GRANT_READ_URI_PERMISSION);
   cameraIntent.setFlags(FLAG_GRANT_WRITE_URI_PERMISSION);
}
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

问题归结为如何在上面的 sn-p 中创建 newFile,因为 getExternalStoragePublicDirectory() 由于范围存储而不再可用。 我已经阅读了documentation 和各种帖子,但这个问题似乎很广泛和模糊。请避免发布指向MediaStore API 的裸链接。

【问题讨论】:

  • 您对“应用程序保留内存”的定义是什么?请注意,该术语目前在the Android SDK documentation 中未使用。
  • CommonsWare 确实如此。我并不是指文档中使用的任何术语。我的意思是,卸载应用程序时删除的任何类型的内存。
  • CommonsWare 换句话说,如果可能的话,我想将我的图片保存在 SharedPreferences 中。
  • 使用FileProvidergetUriForFile() 提供internal storage 中的位置,例如getFilesDir() 上的Context。在您拥有outputFileUriACTION_IMAGE_CAPTURE 请求中使用Uri
  • CommonsWare 谢谢你,解决了我的问题。

标签: android image android-gallery scoped-storage


【解决方案1】:

您可以改用 SAF(存储访问框架)。

使用 SAF 创建文件:

Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_TITLE, "myImage.jpg");

startActivityForResult(intent, your-request-code);

然后在onActivityResult中抓取uri:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == your-request-code && resultCode == Activity.RESULT_OK && data != null) {
        Uri uri = data.getData(); //Do stuff...
    }
}

参考:Access documents and other files from shared storage

【讨论】:

  • 谢谢。使用这种方法,文件是否会保存在内部存储中?
  • @Massimo Frittelli 这个电话用户可以选择他/她想要的任何位置。
  • Hamed 谢谢,我会看看这个方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多