2010年7月6日 星期二

Android學習筆記 - 存取SD卡

1. 由於寫入資料到SD卡是有需要額外的權限,因此需在AndroidManifest.xml允許存取android.permission.WRITE_EXTERNAL_STORAGE這個權限。

2.AccessSDCardExample.java
package tw.nicky;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;

public class AccessSDCardExample extends Activity {

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //判斷SD卡是否存在
        if(!Environment.getExternalStorageState().equals(Environment.MEDIA_REMOVED) ){
            try {
             //取得SD卡路徑
                File SDCardpath = Environment.getExternalStorageDirectory();
                File myDataPath = new File( SDCardpath.getAbsolutePath() + "/myData" );
                if( !myDataPath.exists() ) myDataPath.mkdirs();
                //將資料寫入到SD卡
                FileWriter myFile = new FileWriter( SDCardpath.getAbsolutePath() + "/myData/test.txt" );
                myFile.write("This is a test.");
                myFile.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
         }
    }
}

3. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="tw.nicky"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AccessSDCardExample"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest> 


4. SD卡內容

1 則留言: