提问者:小点点

Environment.GetExternalStorageDirectory()在API级别29 Java中已弃用


在android Java上工作,最近将SDK更新到API级别29,现在有一个警告显示

API级别29中不推荐使用Environment.GetExternalStorageDirectory()

我的代码是

private void saveImage() {

if (requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

    final String folderPath = Environment.getExternalStorageDirectory() + "/PhotoEditors";
    File folder = new File(folderPath);
    if (!folder.exists()) {
        File wallpaperDirectory = new File(folderPath);
        wallpaperDirectory.mkdirs();
    }


    showLoading("Saving...");
    final String filepath=folderPath
                + File.separator + ""
                + System.currentTimeMillis() + ".png";
    File file = new File(filepath);

    try {
        file.createNewFile();
        SaveSettings saveSettings = new SaveSettings.Builder()
                .setClearViewsEnabled(true)
                .setTransparencyEnabled(true)
                .build();
        if(isStoragePermissionGranted() ) {
            mPhotoEditor.saveAsFile(file.getAbsolutePath(), saveSettings, new PhotoEditor.OnSaveListener() {
            @Override
            public void onSuccess(@NonNull String imagePath) {
                hideLoading();
                showSnackbar("Image Saved Successfully");
                mPhotoEditorView.getSource().setImageURI(Uri.fromFile(new File(imagePath)));
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.fromFile(new File(filepath))));
                Intent intent = new Intent(EditImageActivity.this, StartActivity.class);
                startActivity(intent);
                finish();

            } 

            @Override
            public void onFailure(@NonNull Exception exception) {
                hideLoading();
                showSnackbar("Failed to save Image");
            }
       });
   }

还有什么替代方案呢?


共3个答案

匿名用户

使用GetExternalFilesDir()GetExternalCacheDir()GetExternalMediaDir()(Context上的方法)代替环境。GetExternalStorageDirectory()

或者,修改MPhotoEditor使其能够使用URI,则:

>

  • 使用action_create_documentURI获取到用户选择的位置,或者

    使用MediastoreContentResolverInsert()获取特定类型媒体(例如,图像)的URI-请参阅演示如何从网站下载MP4视频的示例应用程序

    另外,请注意,您的uri.fromfileaction_media_scanner_scan_file应该会在Android 7.0+上以fileURIExposedException崩溃。 在Android Q上,只有mediastore/insert()选项可以快速地通过mediastore对内容进行索引。

    有关Android Q如何影响外部存储的更多信息,请参阅这篇博文。

  • 匿名用户

    使用新的API调用获取destPath:

    String destPath = mContext.getExternalFilesDir(null).getAbsolutePath();
    

    匿名用户

    在Android 10中创建文件时,请使用GetExternalFilesDir()GetExternalCachedir()而不是Environment.GetExternalStorageDirectory()

    见下一行:

    val file = File(this.externalCacheDir!!.absolutePath, "/your_file_name")