0

我计划为我现有的应用程序实施范围存储。我所有的应用程序数据都存储在外部存储器的storage/emulated/0/MyAppName路径中。我必须将此数据移动到像Android/data/com.myapp这样的私人文件夹。任何人都可以提供一些代码片段来帮助解决这方面的问题吗?

4

2 回答 2

1

您还可以使用特定于应用程序的文件。首先,让我们考虑您的应用程序 ID 是com.myapp

现在将以下内容添加到应用程序属性内的清单文件中

<application...>            
    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>
</application>
  1. 现在转到res项目中的目录,右键单击它并选择new,然后选择Android Resource Directory.

  2. 现在选择资源类型为xml,将目录名写为xml,源设置为main src/main/res

  3. 现在在具有名称的 xml 文件夹中创建一个新的 xml 文件file_paths

  4. 并在其中写下以下内容。

    <?xml version="1.0" encoding="utf-8"?>
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images"
        path="Android/data/com.myapp/files/Pictures" />
    <external-path name="my_documents"
        path="Android/data/com.myapp/files/Documents" />
    <external-path name="my_videos"
        path="Android/data/com.myapp/files/Movies" />
    </paths>
    

现在要使用它,您可以使用以下代码

private File createImageFile(String fileName) throws IOException {
    File storageDir = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File imageFile = File.createTempFile(fileName, ".jpg", storageDir);
    return imageFile;
}

public Uri getFileUri(String fileName, String imageString) {
    File imageFile = null;
    Uri uri = null;

    try {
        imageFile = createImageFile(fileName);

        imageFile.createNewFile();
        FileOutputStream fo = new FileOutputStream(imageFile.getPath());
        fo.write(imageString.getBytes());
        fo.flush();
        fo.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (imageFile != null) {
        uri = FileProvider.getUriForFile(activity, "com.myapp", imageFile);
    }
    return uri;
}
于 2020-11-10T07:56:24.147 回答
1

在这个SO 主题中,您有一些示例如何将文件移动到新目录(简而言之:使用类中的renameTo方法File

请记住,当您更新targetSdkVersion并“打开”Scoped Storage 时,您将无法访问旧文件夹。在第一个带有文件移动片段的版本中,让用户运行您的应用程序一段时间(大多数活跃用户会将文件移动到新文件夹),然后发布具有 Scoped Storage 支持的新应用程序版本

您必须考虑到部分用户可能会使用(非常)旧的应用程序,并且有朝一日会直接更新到支持 Scoped-Storage(targetSdkVersion增加),他们将丢失数据(上一个文件夹中的文件访问权限)。您将在市场上使用移动文件代码保留版本预范围存储的时间更长 - 一小部分用户将丢失数据

于 2020-11-10T07:00:29.937 回答