我正在尝试在设备存储中对我的应用程序的数据库进行本地备份。我创建了一个备份文件/目录,但我希望用户能够限制从设备复制/删除文件/目录。
是否可以通过代码使用我正在运行的服务实现此目的?
答案 0 :(得分:0)
检查用户是否具有在外部存储上写入的权限的方法。
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” />
快乐的编码!!