【问题标题】:How to create a file in external storage and set permission programmatically如何在外部存储中创建文件并以编程方式设置权限
【发布时间】:2017-11-10 10:14:21
【问题描述】:

我正在尝试在设备存储中对我的应用程序数据库进行本地备份。我创建了一个备份文件/目录,但我希望用户限制从设备复制/删除文件/目录。

是否可以通过代码使用我正在运行的服务来实现这一点?

【问题讨论】:

  • 您是否试图限制从其他应用程序(例如文件资源管理器)复制/粘贴?
  • 这是不可能的。除非您在 getFilesDir() 中进行备份。您的数据库现在所在的同一位置。
  • @Jordan 是的。如果我也可以隐藏它也可以。但是我尝试在目录名称之前添加一个 (.),但它在文件资源管理器中可见。
  • @greenapps 我想要一个数据库备份,用户下次安装我们的应用程序时将能够加载数据。所以我不希望它在卸载时被删除,设备也已植根。
  • 那是不可能的。

标签: java android service background-service


【解决方案1】:

检查用户是否有权限写入外部存储的方法。

public static boolean canWriteOnExternalStorage() {
// get the state of your external storage
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
 // if storage is mounted return true
  Log.v(“sTag”, “Yes, can write to external storage.”);
  return true;
 }
 return false;
}

然后让我们使用这段代码来实际写入外部存储:

// get the path to sdcard
File sdcard = Environment.getExternalStorageDirectory();
// to this path add a new directory path
File dir = new File(sdcard.getAbsolutePath() + “/your-dir-name/”);
// create this directory if not already created
dir.mkdir();
// create the file in which we will write the contents
File file = new File(dir, “My-File-Name.txt”);
FileOutputStream os = outStream = new FileOutputStream(file);
String data = “This is the content of my file”;
os.write(data.getBytes());
os.close();

您需要以下权限

<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE” />

编码愉快!!

【讨论】:

  • 我已经完成了这些步骤。我可以复制 db 文件,但我无法设置目录的权限以使其隐藏/不可删除。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-05
  • 2014-11-20
  • 1970-01-01
相关资源
最近更新 更多