[英]How to create a public directory on the external storage?
我正在嘗試將公共文件保存在外部存儲中。 我正在從Android開發人員頁面關注以下示例: https : //developer.android.com/training/data-storage/files#PublicFiles
首先,我嘗試在公共目錄DIRECTORY_DOCUMENTS中創建目錄“ mydocuments”。 代碼很簡單
TextView tv= findViewById(R.id.myTextview);
// Get the directory for the user's public pictures directory.
File documents= Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOCUMENTS);
tv.append("\n documents directory=" + documents);
File file = new File(documents, "mydocuments");
tv.append("\n\nDirectory to be created=" + file);
if (file.exists())
tv.append("\n\nFile already exists:" + file.getAbsolutePath());
else{
if (!file.mkdirs())
tv.append("\n\nDirectory not created:" + file.getAbsolutePath());
我在清單文件中添加了權限
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE">
</uses-permission>
但是,當我在虛擬或物理設備中運行此命令時,結果始終相同:
documents directory=/storage/emulated/0/Documents
Directory to be created=/storage/emulated/0/Documents/mydocuments
Directory not created:/storage/emulated/0/Download/mydocuments
如何使Documents目錄可寫?
先感謝您。
您今年遇到這個問題的排名是#1278。
對於Android 6+,您必須添加代碼以要求用戶確認清單文件中要求的權限。
Google的運行時權限。
您也可以轉到應用程序的設置,然后將存儲權限切換為開啟。
感謝@greenapps的建議,我解決了我的問題。 這是我發現寫在SD卡上Documents目錄中的最簡單的解決方案,如
https://developer.android.com/training/permissions/requesting
1.-首先在代碼開頭的某處詢問用戶權限:
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS);
我之前定義常量的地方
final int MY_PERMISSIONS=1;
2.-然后實現我上面的代碼以在方法內部寫入SD卡
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// task you need to do.
writeSD(); // this is the code to write on the SD card shown above
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
tv.append("\n\n No permission given");
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
這為我解決了這個問題。 第一次執行時,會打開一個對話框,詢問權限。 之后,允許讀取sdcard的內容並寫入公共目錄DOCUMENTS,PICTURES,DOWNLOADS等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.