我使用阿迪爾土耳其人許可建議刪除權限下面給出的過程僅僅是6.0其他Android OS permossion將被授予。我不需要檢查構建版本,因爲我只使用Android 6(API 23)。
//
// Get storage write permission
//
public boolean isStoragePermissionGranted(int requestCode) {
if (ContextCompat.checkSelfPermission(MyActivity.this,android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
//Now you have permission
return true;
} else {
ActivityCompat.requestPermissions(MyActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
return false;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Now you have permission
// Check file copy generated the request
// and resume file copy
if(requestCode == WFileRequest)
try {
copyFile(OriginalDataFileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
雖然這通過允許例外了,它並沒有回答如何將默認的應用程序目錄外部創建一個文件夾的問題。下面的代碼獲取權限,並在/ storage/emulated/0上創建一個名爲AppData的文件夾,它出現在設備存儲的頂層。在Adeel Turk的例子中,權限請求代碼WFileRequest被設置爲4,但我知道你可以使用任何數字。然後,權限請求回調將檢查請求代碼,並再次使用最初寫入的文件的名稱調用copyFile例程。
大部分代碼使用的例子,從這個論壇一對夫婦的其他職位在how to create a folder in android External Storage Directory?和How to copy programmatically a file to another directory?
public void copyFile(String SourceFileName) throws FileNotFoundException, IOException
{
String filepath = "";
//
// Check permission has been granted
//
if (isStoragePermissionGranted(WFileRequest)) {
//
// Make the AppData folder if it's not already there
//
File Directory = new File(Environment.getExternalStorageDirectory() + "/AppData");
Directory.mkdirs();
Log.d(Constants.TAG, "Directory location: " + Directory.toString());
//
// Copy the file to the AppData folder
// File name remains the same as the source file name
//
File sourceLocation = new File(getExternalFilesDir(filepath),SourceFileName);
File targetLocation = new File(Environment.getExternalStorageDirectory() + "/AppData/" + SourceFileName);
Log.d(Constants.TAG, "Target location: " + targetLocation.toString());
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
來源
2016-11-12 22:48:17
Max
棉花糖需要在運行時檢查,以檢查權限此https://developer.android.com/training/permissions /requesting.html – Nakul