繁体   English   中英

Android,如何防止卸载应用程序时删除内部存储文件

[英]Android, how to prevent internal storage files to be deleted when the app is uninstalled

我正在开发一个应用程序,它在两个 .xml 文件中存储了一些设置,保存在内部存储中。 我需要将它们保存在那里,所以请不要回答我“将它们保存在 SD 卡上”。

我尝试卸载然后重新安装(从 Android Studio)我的应用程序以查看android:allowBackup="true"也适用于内部存储的文件,但答案是否定的。

这是因为我从 IDE 完成了重新安装,还是需要在某处添加一些代码?

感谢帮助。

您可以使用Environment.getExternalStorageDirectory()保存这些文件。该文件存储在外部存储设备上。 不要将术语“外部存储”称为SD卡感到困惑。 SD卡是辅助外部存储。 但是Environment.getExternalStorageDirectory()返回设备主要外部存储的顶级目录,该目录基本上是不可移动的存储。

因此文件路径可以是/storage/emulated/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 Manifest中添加以下权限

<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();
   }

从 API 级别 29 开始,有“hasFragileUserData”清单标志

该文件指出

如果为 true,则会提示用户在卸载时保留应用程序的数据。 可能是布尔值,例如“true”或“false”。

示例代码:

<application
  ....
  android:hasFragileUserData="true">

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM