将Android 11中的文件保存到外部存储(SDK 30)

问题描述 投票:0回答:5

我正在 Android 11(SDK 版本 30)上编写一个新应用程序,但我根本找不到关于如何将文件保存到外部存储的示例。

我阅读了他们的文档,现在知道他们基本上忽略了清单权限(

READ_EXTERNAL_STORAGE
WRITE_EXTERNAL_STORAGE
)。他们还忽略了 manifest.xml 应用程序标记中的
android:requestLegacyExternalStorage="true"

在他们的文档https://developer.android.com/about/versions/11/privacy/storage他们写道,您需要启用

DEFAULT_SCOPED_STORAGE
FORCE_ENABLE_SCOPED_STORAGE
标志以在您的应用程序中启用范围存储。

我必须在哪里启用这些? 当我完成后,如何以及何时获得写入外部存储的实际权限?有人可以提供工作代码吗?
我想保存 .gif、.png 和 .mp3 文件。所以我不想写信给画廊。

提前致谢。

android file permissions android-external-storage android-11
5个回答
28
投票

对应所有Api,包括Api 30, Android 11 :

public static File commonDocumentDirPath(String FolderName)
{
    File dir = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
    {
        dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + "/" + FolderName);
    }
    else
    {
        dir = new File(Environment.getExternalStorageDirectory() + "/" + FolderName);
    }

    // Make sure the path directory exists.
    if (!dir.exists())
    {
        // Make it, if it doesn't exit
        boolean success = dir.mkdirs();
        if (!success)
        {
            dir = null;
        }
    }
    return dir;
}

现在,使用这个

commonDocumentDirPath
保存文件。

来自评论的旁注,

getExternalStoragePublicDirectory
某些范围现在可以与 Api 30、Android 11 一起使用。干杯!感谢 CommonsWare 提示。


8
投票

您可以将文件保存到外部存储的公共目录中。

喜欢文档、下载、DCIM、图片等。

像 10 版之前一样的通常方式


7
投票

**最简单的答案和测试(Java)**

private void createFile(String title) {
        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("text/html");
        intent.putExtra(Intent.EXTRA_TITLE, title);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Uri.parse("/Documents"));
    }
    createInvoiceActivityResultLauncher.launch(intent);
}

private void createInvoice(Uri uri) {
    try {
        ParcelFileDescriptor pfd = getContentResolver().
                openFileDescriptor(uri, "w");
        if (pfd != null) {
            FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
            fileOutputStream.write(invoice_html.getBytes());
            fileOutputStream.close();
            pfd.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

/////////////////////////////////////////////////////
// You can do the assignment inside onAttach or onCreate, i.e, before the activity is displayed


    String invoice_html;
    ActivityResultLauncher<Intent> createInvoiceActivityResultLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

       invoice_html = "<h1>Just for testing received...</h1>";
       createInvoiceActivityResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        // There are no request codes
                        Uri uri = null;
                        if (result.getData() != null) {
                            uri = result.getData().getData();
                            createInvoice(uri);
                            // Perform operations on the document using its URI.
                        }
                    }
                });

4
投票

我正在使用这个方法,它真的对我有用 我希望我能帮助你。有什么不明白的可以随时问我

   Bitmap imageBitmap;

   OutputStream outputStream ;
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
            {
                ContentResolver resolver = context.getContentResolver();
                ContentValues contentValues = new ContentValues();
                contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME,"Image_"+".jpg");
                contentValues.put(MediaStore.MediaColumns.MIME_TYPE,"image/jpeg");
                contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH,Environment.DIRECTORY_PICTURES + File.separator+"TestFolder");
                Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues);
                try {
                    outputStream =  resolver.openOutputStream(Objects.requireNonNull(imageUri) );
                    imageBitmap.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
                    Objects.requireNonNull(outputStream);
                    Toast.makeText(context, "Image Saved", Toast.LENGTH_SHORT).show();
                    
                } catch (Exception e) {
                    Toast.makeText(context, "Image Not Not  Saved: \n "+e, Toast.LENGTH_SHORT).show();
    
                    e.printStackTrace();
                }
    
            }

清单文件(添加权限)

<uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION" />

0
投票

我知道这个问题有点老了,但这里有一个有效的解决方案,可以在除手机根目录之外的任何地方组织文件

首先在您的 build.gradle 文件中,实现 SAF 框架的 DocumentFile 类:

implementation 'androidx.documentfile:documentfile:1.0.1'

下一步调用此方法请求 SAF 的操作权限(您只需在用户安装时执行一次):

 private void requestDocumentTreePermissions() {
    // Choose a directory using the system's file picker.
    new AlertDialog.Builder(this)
            .setMessage("*Please Select A Folder For The App To Organize The Videos*")
            .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                @RequiresApi(api = Build.VERSION_CODES.Q)
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    StorageManager sm = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
                    Intent intent = sm.getPrimaryStorageVolume().createOpenDocumentTreeIntent();

                    String startDir = "Documents";
                    Uri uri = intent.getParcelableExtra("android.provider.extra.INITIAL_URI");

                    String scheme = uri.toString();


                    scheme = scheme.replace("/root/", "/document/");
                    scheme += "%3A" + startDir;

                    uri = Uri.parse(scheme);
                    Uri rootUri = DocumentsContract.buildDocumentUri(
                            EXTERNAL_STORAGE_PROVIDER_AUTHORITY,
                            uri.toString()
                    );
                    Uri treeUri = DocumentsContract.buildTreeDocumentUri(
                            EXTERNAL_STORAGE_PROVIDER_AUTHORITY,
                            uri.toString()
                    );
                    uri = Uri.parse(scheme);
                    Uri treeUri2 = DocumentsContract.buildTreeDocumentUri(
                            EXTERNAL_STORAGE_PROVIDER_AUTHORITY,
                            uri.toString()
                    );
                    List<Uri> uriTreeList = new ArrayList<>();
                    uriTreeList.add(treeUri);
                    uriTreeList.add(treeUri2);
                    getPrimaryVolume().createOpenDocumentTreeIntent()
                            .putExtra(EXTRA_INITIAL_URI, rootUri);
                    Intent intent2 = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
                    // Optionally, specify a URI for the directory that should be opened in
                    // the system file picker when it loads.
                    intent2.addFlags(
                            Intent.FLAG_GRANT_READ_URI_PERMISSION
                                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                                    | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
                                    | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION);
                    intent2.putExtra(EXTRA_INITIAL_URI, rootUri);
                    startActivityForResult(intent2, 99);
                }
            })
            .setCancelable(false)
            .show();


}

下一步存储一些持久权限:

    @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 99 && resultCode == RESULT_OK) {
        //get back the document tree URI (in this case we expect the documents root directory)
        Uri uri = data.getData();
        //now we grant permanent persistant permissions to our contentResolver and we are free to open up sub directory Uris as we please until the app is uninstalled
        getSharedPreferences().edit().putString(ACCESS_FOLDER, uri.toString()).apply();
        final int takeFlags = (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        getApplicationContext().getContentResolver().takePersistableUriPermission(uri, takeFlags);
        //simply recreate the activity although you could call some function at this point
        recreate();
    }
}

您可以在正确的文件上调用 documentFile 的重命名方法

DocumentFile df = DocumentFile.fromTreeUri(MainActivity.this, uri);
df = df.findFile("CurrentName")
df.renameTo("NewName");

您还可以使用您的内容解析器打开 InputStreams 和 OutputStreams,因为使用以下代码段授予该文档文件的内容解析器持久的 URI 权限:

getContentResolver().openInputStream(df.getUri());
getContentResolver().openOutputStream(df.getUri());

InputStreams 用于读取,OutputStreams 用于保存

您可以使用列表文件

df.listFiles();

或者您可以使用以下方式列出文件:

public static DocumentFile findFileInDirectoryMatchingName(Context mContext, Uri mUri, String name) {
    final ContentResolver resolver = mContext.getContentResolver();
    final Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(mUri,
            DocumentsContract.getDocumentId(mUri));
    Cursor c = null;
    try {
        c = resolver.query(childrenUri, new String[]{
                DocumentsContract.Document.COLUMN_DOCUMENT_ID,
                DocumentsContract.Document.COLUMN_DISPLAY_NAME,
                DocumentsContract.Document.COLUMN_MIME_TYPE,
                DocumentsContract.Document.COLUMN_LAST_MODIFIED

        }, DocumentsContract.Document.COLUMN_DISPLAY_NAME + " LIKE '?%'", new String[]{name}, null);
        c.moveToFirst();
        while (!c.isAfterLast()) {
            final String filename = c.getString(1);
            final String mimeType = c.getString(2);
            final Long lastModified = c.getLong(3);
            if (filename.contains(name)) {
                final String documentId = c.getString(0);
                final Uri documentUri = DocumentsContract.buildDocumentUriUsingTree(mUri,
                        documentId);

                return DocumentFile.fromTreeUri(mContext, documentUri);
            }
            c.moveToNext();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (c != null) {
            c.close();
        }
    }

    return null;
}

这将比 df.listFiles() 方法运行得更快

Src(这是我自己的实现,但这是原始的 SF 问题) 在针对 Android 11 (Api 30) 时重命名视频/图像

© www.soinside.com 2019 - 2024. All rights reserved.