Android sdcard讀寫權限問題之一

來源:互聯網
上載者:User

標籤:android   style   blog   code   c   tar   

博主在剛剛在學習過程中發現了一個關於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搞定



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.