当我使用调试器时,sd.canWrite()语句返回false并且不运行其余代码。我尝试使用模拟器和实际的三星平板电脑。 我有
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
在我的清单中。
public void exportDatabse(String databaseName) {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//"+getPackageName()+"//databases//"+databaseName+"";
String backupDBPath = "backupname.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
Log.d("file", "file copied2");
if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
}
Log.d("file", "file copied3");
}
} catch (Exception e) {
Log.d("file", "file not copied");
}
Log.d("file", "method runs");
}
答案 0 :(得分:1)
请检查外部存储器是否写保护 -
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
}
答案 1 :(得分:1)
如果您使用的是在Android 6.0或更高版本上运行的模拟器或系统您必须为Critical or Dangerous Permissions添加运行时权限
确保您的活动实施OnRequestPermissionResult
。然后做
boolean permission = isStoragePermissionGranted();
if(permission){
//DO YOUR TASK HERE
}
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted");
return true;
} else {
Log.v(TAG,"Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
回调功能
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
//resume tasks needing this permission
}
}