博主在剛剛在學習過程中發現了一個關於android往sdcard讀寫的問題,
配置了該配置的提示無讀寫權限。
在AndroidManifest.xml檔案中配置清單如下
package="com.example.custom"
android:versionCode="1"
android:versionName="1.0" >
android:minSdkVersion="8"
android:targetSdkVersion="19" />
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:name="custom_content_provider.RegionContentProvider"
android:authorities="mobile.android.wang.hao.regioncontent" />
往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搞定