2016-04-24 353 views
1

我有這種看似簡單的代碼ContentResolver的openInputStream()拋出在現有文件

File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); 
File testfile = new File(path,"image.jpg"); 

Log.d(TAG,"testfile: " + testfile + " exists: " + testfile.exists()); 

Uri uri = Uri.fromFile(testfile); 
ContentResolver cr = context.getContentResolver(); 
InputStream istr = cr.openInputStream(uri); 

輸出是FileNotFound:

testfile: /storage/emulated/0/Pictures/image.jpg exists: true 

的URI值是file:///storage/emulated/0/Pictures/image.jpg。看起來像是同一個文件,但openInputStream()拋出FileNotFoundException。

任何想法爲什麼?這是在Android 6.0.1上。

+1

你的清單中有'READ_EXTERNAL_STORAGE'或'WRITE_EXTERNAL_STORAGE'' 元素嗎?如果你的'targetSdkVersion'是23或更高,你是否在運行時請求了許可?有關更多可能性,請參見https://commonsware.com/blog/2015/08/31/hey-where-did-my-permission-go.html。 – CommonsWare

+0

是的,正確的。 targetSdkVersion是23,我沒有請求權限。謝謝。被困惑,因爲它在過去... – farindk

回答

1

此權限添加到您的AndroidManifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

當targetSdkVersion爲23以上(安卓6),把這個在AndroidManifest.xml是不夠的,你必須在運行時要求的權限。

+0

這是在我的AndroidManifest.xml,但正如'CommonsWare'在對我的問題的評論中提到的,我增加了targetSdkVersion 23,現在必須在運行時請求權限。我已經將此添加到您的答案中。 – farindk

相關問題