问题描述
我计划为现有应用程序实现范围存储。我所有的应用程序数据都存储在外部存储器的 storage / emulated / 0 / MyAppName 路径中。我必须将此数据移到 Android / data / com.myapp 之类的私有文件夹中。谁能在这方面提供一些代码段来帮助您?
解决方法
在此SO topic中,您有一些示例如何将文件移动到新目录(简而言之:使用renameTo
类中的File
方法)
请记住,当您更新targetSdkVersion
并“打开”作用域存储时,您将无法访问旧文件夹。带有文件移动摘要的第一个发行版本,让用户运行您的应用一段时间(大多数活动用户会将文件移动到新文件夹),然后发布具有范围存储支持的新应用版本
您必须考虑到,部分用户可能会使用(非常)旧的应用程序,并且某天会直接更新为支持范围存储(targetSdkVersion
),他们将丢失数据(上一个文件夹中的文件访问)。更长的时间,您将在市场上移动文件代码的情况下将版本保持在预限定范围内-较小部分的用户将丢失数据
您还可以使用特定于应用程序的文件。
首先,让我们考虑您的应用程序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>
-
现在转到项目中的
res
目录,右键单击它并选择new
,然后选择Android Resource Directory
。 -
现在选择资源类型为
xml
,将目录名称输入为xml
,并将源设置为main src/main/res
-
现在在名称为
file_paths
的xml文件夹中创建一个新的xml文件 -
并在其中写以下内容。
<?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;
}