1. 程式人生 > >Android sdcard讀寫權限問題之中的一個

Android sdcard讀寫權限問題之中的一個

equal pac end label fin try filter admin sso

博主在剛剛在學習過程中發現了一個關於android往sdcard讀寫的問題,

配置了該配置的提示無讀寫權限。

在AndroidManifest.xml文件裏配置清單例如以下


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.custom"
android:versionCode="1"
android:versionName="1.0" >

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<provider
android:name="custom_content_provider.RegionContentProvider"
android:authorities="mobile.android.wang.hao.regioncontent" />
<activity android:name="custom_content_provider.Main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>


往sdcard寫文件的代碼例如以下

//打開數據庫
private SQLiteDatabase openDatabase(){
Log.d("error", "openDatabase");
InputStream is = null;
FileOutputStream fos = null;
try{

if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){

//獲取文件文件夾
String dbFileName = Environment.getExternalStorageDirectory()+"/region.db";

Log.d("error", dbFileName);
if(!(new File(dbFileName).exists())){ //文件不存在copy
is = getContext().getResources().getAssets().open("region.db");
fos = new FileOutputStream(dbFileName);
byte[] buffer = new byte[8192];
int count = 0;
while((count=is.read(buffer))>0){
fos.write(buffer,0,count);
}
}
}else{
Log.d("error", "無讀寫權限"+Environment.getExternalStorageDirectory()+"/region.db");
}
}catch(Exception ex){
Log.d("error", ex.getMessage());
}finally{
// 關閉流 略...
}
return null;


然後執行的時候提示無權限訪問該sdcard路徑,可是我們配置的也配置了。網上有說是sdk版本號的問題,

說2.2以後的版本號不能用FileOutputStream 創建文件,搞了半天。還是一樣,最後我用手機測試了一下,

發現文件創建成功,突然。我想了一下,是否有sdcard呢?


技術分享 技術分享

d---------,問題竟然出在這裏,難道是虛擬機沒有裝載sdcard。緊接著,我重新啟動了一把。OK搞定

技術分享


Android sdcard讀寫權限問題之中的一個