編輯:關於 Android 程式設計
傲不可長,欲不可縱,樂不可極,志不可滿。—— 魏 徵
本講主題:SD 卡。
前一講談到用 File 做資料儲存,但那類檔案是存在應用程式自己的私有目錄裡,容量受限。當你要存的是電影、錄音、大量圖片這種量級的檔案時,就必須把資料寫到外部儲存空間,也就是俗稱的 SD 卡。
Android 把外部儲存空間的相關操作都集中在 Environment 類別中,常用的方法如下:
public static File getDataDirectory() // 取得 data 目錄 public static File getDownloadCacheDirectory() // 取得 Download/Cache 目錄 public static File getExternalStorageDirectory() // 取得外部儲存空間(SD 卡)根目錄 public static String getExternalStorageState() // 取得外部儲存空間目前狀態 public static File getRootDirectory() // 取得系統 root 目錄
搭配判斷狀態的常用常數:
String MEDIA_MOUNTED // 已掛載,可讀可寫 String MEDIA_MOUNTED_READ_ONLY // 已掛載,唯讀
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/c1"
tools:context="com.example.text1.MainActivity$PlaceholderFragment" >
<EditText
android:id="@+id/edit"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/write"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="寫入" />
<Button
android:id="@+id/read"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="讀取" />
</LinearLayout>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.text1"
android:versionCode="1"
android:versionName="1.0" >
<!-- 在 SD 卡中建立與刪除檔案 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<!-- 往 SD 卡寫入資料 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" />
</manifest>
public class MainActivity extends Activity implements OnClickListener {
private static final String FILE_NAME = "text.txt";
private Button write;
private Button read;
EditText edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViews();
}
private void findViews() {
edit = (EditText) findViewById(R.id.edit);
write = (Button) findViewById(R.id.write);
read = (Button) findViewById(R.id.read);
write.setOnClickListener(this);
read.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.write:
// 寫入前務必先確認外部儲存空間已掛載
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String content = edit.getText().toString();
try {
// 取得 SD 卡根路徑
File dir = Environment.getExternalStorageDirectory();
String sdcardPath = dir.getAbsolutePath(); // 例如 /mnt/sdcard
Toast.makeText(MainActivity.this,
"目錄為:" + sdcardPath,
Toast.LENGTH_SHORT).show();
File file = new File(dir, FILE_NAME);
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(file.length()); // 指標移到檔尾,改成附加寫入
raf.write(content.getBytes());
raf.close();
} catch (Exception e) {
e.printStackTrace();
}
}
break;
case R.id.read:
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
StringBuilder sb = new StringBuilder();
try {
File dir = Environment.getExternalStorageDirectory();
File file = new File(dir, FILE_NAME);
InputStream inputStream = new FileInputStream(file);
int len = 0;
byte[] buffer = new byte[1024];
while ((len = inputStream.read(buffer)) != -1) {
sb.append(new String(buffer, 0, len));
}
Toast.makeText(MainActivity.this,
"內容為:" + sb.toString(),
Toast.LENGTH_SHORT).show();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
break;
}
}
}
1. 權限模型已經改變。上面這份程式碼是 Android 4.x 時代的寫法。從 Android 6.0(API 23)開始,WRITE_EXTERNAL_STORAGE 屬於「危險權限」,除了要在 Manifest 宣告,還必須在執行期透過 requestPermissions() 動態向使用者詢問,並處理使用者按下「拒絕」的情況。Android 4.4(API 19)起,MOUNT_UNMOUNT_FILESYSTEMS 也不再對一般應用開放。
2. 建議改用 App 專屬目錄。直接寫到外部儲存空間根目錄會造成檔案散亂,也容易被其他應用掃到。較好的做法是寫入 getExternalFilesDir() 或 getExternalCacheDir() 回傳的 App 專屬目錄——這個路徑不需要任何權限,且 App 解除安裝時系統會自動清理。
3. 建議改用串流或 Storage Access Framework。範例中的 RandomAccessFile 是為了示範隨機存取;若只是整檔讀寫,用 FileOutputStream / FileInputStream 或 File API 都更直觀。而從 Android 10(API 29)起,系統導入 Scoped Storage,直接操作檔案路徑的方式已大幅受限,跨應用讀寫檔案應改用 ContentResolver 或 Storage Access Framework。
本講就到這裡,謝謝大家!
Android 學習筆記:應用單元測試實例分析
本文結合學習筆記的形式,梳理 Android 應用中單元測試的完整實現步驟,供大家參考。 第一步:配置 AndroidManifest.xml 在清單文件中加入以下兩段
Android 畫布的移動與翻轉技巧
Canvas 的變換在圖像處理上是一大利器。靠著 translate 與 rotate,不必進行陣列的轉置顛倒等繁瑣運算,就能輕鬆改變原點位置與方向。 初始狀態下,畫
Android 屬性動畫深度剖析:從傳統動畫的先天缺陷說起
一句話說清主題 做產品時,恰到好處的動畫能顯著提升用戶體驗,平移、縮放、旋轉都是常見手法。這類動畫在 Android 早期版本就已具備,我們習慣稱之為「傳統動畫」,它分為
Android 音樂播放器實作(二十):下載完成後通知主界面刷新本地音樂列表
本篇要解決的問題:歌曲下載完成之後,主界面要能自動更新本地音樂列表。 除了下面要講的這個環節,專案裡還有一些待修的 BUG,後續文章會持續補充。 一、問題與解法 下載完