我正在开发一个应用程序,该应用程序存储在两个.xml文件中,保存在内部存储上。我需要将它们保存在那里,所以请不要回答我"在SD卡上保存它们"。
我尝试卸载然后重新安装(来自Android Studio(我的应用程序,以查看android:allowBackup="true"
是否也适用于内部存储的文件,但答案是否。
这是因为我从IDE重新安装了重新安装,还是需要在某个地方添加一些代码?
感谢您的帮助。
启动API级别29有" Hasfragileuserdata"清单标志
文档指出
如果提示用户将应用程序的数据保留在卸载上。可能是布尔值,例如" true"或" false"。
示例代码:
<application
....
android:hasFragileUserData="true">
您可以使用Environment.getExternalStorageDirectory()
保存这些文件,然后将其存储在外部存储设备上。不要将外部存储术语作为SD卡混淆。SD卡是二级外部存储。但是Environment.getExternalStorageDirectory()
返回设备主要外部存储的顶级目录,这基本上是不可移动的存储。
因此,文件路径可以是/storage/emulation/0/yourfolder/my.xml
因此,即使您卸载了该应用程序,这些文件也不会被删除。
您可以使用此片段在主要外部存储中创建文件:
private final String fileName = "note.txt";
private void writeFile() {
File extStore = Environment.getExternalStorageDirectory();
// ==> /storage/emulated/0/note.txt
String path = extStore.getAbsolutePath() + "/" + fileName;
Log.i("ExternalStorageDemo", "Save to: " + path);
String data = editText.getText().toString();
try {
File myFile = new File(path);
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.close();
Toast.makeText(getApplicationContext(), fileName + " saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
不要忘记在Android清单中添加以下权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
您可以如下读取该文件:
private void readFile() {
File extStore = Environment.getExternalStorageDirectory();
// ==> /storage/emulated/0/note.txt
String path = extStore.getAbsolutePath() + "/" + fileName;
Log.i("ExternalStorageDemo", "Read file: " + path);
String s = "";
String fileContent = "";
try {
File myFile = new File(path);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((s = myReader.readLine()) != null) {
fileContent += s + "n";
}
myReader.close();
this.textView.setText(fileContent);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), fileContent, Toast.LENGTH_LONG).show();
}