【问题标题】:Android - Avoid saving to storage/emulated/0Android - 避免保存到 storage/emulated/0
【发布时间】:2016-10-18 08:39:20
【问题描述】:

我正在尝试使用以下代码将图像保存在公共存储目录中。但是,当这是保存到 storage/emulated/0 而不是公共图片文件夹时。我基本上在另一个应用程序中使用了这个确切的代码,它工作得很好。有谁知道为什么 .getExternalStoragePublic 目录没有返回可访问的 /Pictures/ 而是返回 storage/emulated/0 ?

我的清单文件中有“uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE”

File backupFile;
File appFolder;
String path= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/CustomFolder";
appFolder = new File(path);
if (!appFolder.exists())
    appFolder.mkdir();
String fileName = "picture.jpg"
backupFile = new File(appFolder, fileName);
FileOutputStream output = null;
try {
    output = new FileOutputStream(backupFile);
    output.write(bytes);
} catch (IOException e) {
    e.printStackTrace();
} finally {
    mImage.close();
    if (null != output) {
        try {
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

【问题讨论】:

  • appFolder.mkdir(); 检查返回值,因为它可能无法创建目录。如果返回 false 并且不继续执行代码而是返回,则显示 toast。
  • 当您只想说Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() 是一个与您预期不同的文件夹时,您为什么要发布所有这些代码。还是不行?
  • is not returning the accessible /Pictures/ and instead returning storage/emulated/0。它永远不会返回/Pictures/,但它可以返回/storage/emulated/0/Pictures

标签: android image android-studio save public


【解决方案1】:

没关系,我想通了。事实证明,在 Manifest 文件中仅包含“uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" 是不够的,我必须在它之前放置以下代码才能使其工作:

    int CAMERA_PERMISSION_REQUEST_CODE = 2;
    int result = ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
    if (result != PackageManager.PERMISSION_GRANTED){
        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)){
            Toast.makeText(getActivity().getApplicationContext(), "External Storage permission needed. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
        } else {
            ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},CAMERA_PERMISSION_REQUEST_CODE);
        }
    }

【讨论】:

  • 如果这是问题所在,那么您误导了我们,因为您说图像是写的。只是在不同的地方。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-09
  • 1970-01-01
  • 1970-01-01
  • 2014-06-30
  • 2021-05-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多