Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 數據存儲全解:SharedPreferences、內部存儲與 SDCard 讀寫

編輯:關於 Android 程式設計

一、Android 的五種存儲方式

Android 官方把 Data Storage 分成 Storage Options 五類,這是理解後續所有存儲 API 的地基:

1. Shared Preferences
Store private primitive data in key-value pairs.
以鍵值對形式保存簡單的原始數據類型。
2. Internal Storage
Store private data on the device memory.
在手機內存中保存不對外共享的私有數據。
3. External Storage
Store public data on the shared external storage.
在共享的外部存儲上保存公共數據,主要指 SDCard。
4. SQLite Databases
Store structured data in a private database.
把結構化數據存進私有數據庫。
5. Network Connection
Store data on the web with your own network server.
把數據存到自建的遠程服務器上。

幾個容易踩坑的認知問題,先說清楚:

  • 內部存儲空間非常有限,同時又是系統本身和系統應用程序的主要存儲地。一旦內部空間耗盡,手機基本就癱了,所以要盡量節約使用。
  • SharedPreferences 和 SQLite 數據庫都落在內部存儲上,通常通過 Context 來獲取和可操作性。getFilesDir() 返回你 app 在內部存儲上的根目錄。
  • 最容易被誤解的是「外部存儲」。PC 上自帶硬盤算內部存儲、U 盤算外部存儲,於是很多人順手就把手機機身固有存儲當內部、把擴展 SD 卡當外部。但在 Android 編程語境裡不是這樣:比如 Nexus 4 有 16GB 存儲,消費者可以隨便理解,寫代碼時這 16GB 依然屬於外部存儲。

二、SharedPreferences

概念

SharedPreferences 是 Android 提供的通用數據持久化框架,用於存儲和讀取 key-value 形式的原始基本類型對,目前支持 string、int、long、float、boolean 等;自定義對象存不進去。它最典型的用途是保存系統配置信息:上次登錄的用戶名、音效和振動開關、小遊戲的最高積分等等,讓 app 下次啟動時還能延續上次的設置。鍵值對的形式天然適合寫入和讀取。

使用四步

  1. 獲取 SharedPreferences 對象(它本身是接口,不能直接 new)。
  2. 調用 edit() 拿到 SharedPreferences.Editor。
  3. 通過 Editor 的 putXxx() 系列方法寫入數據。
  4. 調用 commit() 提交,這一步之前數據不會落盤。

獲取對象的三種途徑

1. Context.getSharedPreferences(String name, int mode)

第一個參數指定文件名,文件不存在時會新建,落盤路徑是 /data/data/包名/shared_prefs/;第二個參數指定讀寫模式,可選值如下:

  • Context.MODE_PRIVATE:默認模式,數據僅當前應用可讀寫;同名文件會被新內容覆蓋。
  • Context.MODE_APPEND:文件已存在時不新建,改為往原文件追加內容。
  • Context.MODE_MULTI_PROCESS:多進程同時讀寫同一個文件時使用。
  • Context.MODE_WORLD_READABLE:允許其他應用讀但不允許寫,Android 4.2 起已廢棄。
  • Context.MODE_WORLD_WRITEABLE:允許其他應用讀寫,會覆蓋原數據,Android 4.2 起已廢棄。
  • 上述權限可以用 + 位運算組合。

2. Activity.getPreferences(int mode)

與上面那個方法相似,但只有 mode 一個參數,並會自動拿當前 Activity 的類名作為文件名。

3. PreferenceManager.getDefaultSharedPreferences(Context context)

靜態方法,接收一個 Context,會以應用包名作為前綴自動命名。例如包名為 org.mobiletrain.preferenceactivity 的應用,會在 /data/data/org.mobiletrain.preferenceactivity/shared_prefs/ 下生成 org.mobiletrain.preferenceactivity_preferences.xml。

順帶說一下沙盒(sandbox)。每個 app 都有一個放在沙盒中的私有文件目錄,路徑是 /data/data/包名,別的 app 進不去。沙盒這套虛擬化技術在計算機安全領域很常見,原理是通過重定向把程序生成和修改的文件全部導向自身文件夾,讓可疑程序先在隔離環境裡跑,一旦出現惡意行為就直接掐斷,不危害系統。

核心代碼

button_main_savedata.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        prefs = getSharedPreferences("myaccount", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt("age", 38);
        editor.putString("username", "wangxiangjun");
        editor.putString("pwd", "123456");
        editor.putString("username", "xiangjun");   // 同名 key 後寫覆蓋前寫
        editor.commit();
    }
});

button_main_readdata.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        prefs = getSharedPreferences("myaccount", Context.MODE_PRIVATE);
        String name = prefs.getString("username", "wxj");   // 第二個參數是默認值
        String pwd  = prefs.getString("pwd", "000");
        int age     = prefs.getInt("age", 20);
        System.out.println("====>" + name + ":" + pwd + ":" + age);
    }
});

落盤後的文件長什麼樣

SharedPreferences 數據一律以 xml 格式保存在 /data/data/包名/shared_prefs 目錄下:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="pwd">123456</string>
    <string name="username">xiangjun</string>
    <int name="age" value="20" />
</map>

用 PreferenceActivity 做設置頁

手機裡那種系統風格的設置頁面:

如果按傳統思路做,得寫一個繁瑣的布局再加一堆監聽。其實用 PreferenceActivity 會省事很多,步驟是:

  • 把 setting.xml 放到 res/xml 目錄下;
  • 把 arrays.xml 放到 res/values 目錄下;
  • 寫一個 SettingActivity 繼承 PreferenceActivity。

目錄結構:

代碼非常短,注意不再需要 setContentView():

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // setContentView(R.layout.activity_main);
    addPreferencesFromResource(R.xml.setting);
    // 注意:該方法在 API level 11 中被標記為 deprecated,
    // 基於 fragment 的現代 PreferenceActivity 不再使用它。
}

實戰:用 SharedPreferences 做黑名單

public class MainActivity extends Activity {
    private ListView listView_main_blockList;
    private EditText editText_main_number;
    private TextView textView_main_emptyinfo;
    private SharedPreferences prefs = null;
    private Editor editor = null;
    private ArrayAdapter<String> adapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText_main_number = (EditText) findViewById(R.id.editText_main_number);
        listView_main_blockList = (ListView) findViewById(R.id.listView_main_blocklist);
        textView_main_emptyinfo = (TextView) findViewById(R.id.text_main_emptyinfo);

        prefs = getSharedPreferences("blocklist", Context.MODE_PRIVATE);
        editor = prefs.edit();

        List<String> list = getBlocklist();
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
        // setEmptyView():適配器為空時展示的替代視圖
        listView_main_blockList.setEmptyView(textView_main_emptyinfo);
        listView_main_blockList.setAdapter(adapter);
    }

    public void clickButton(View view) {
        switch (view.getId()) {
            case R.id.button_main_add:
                String mpnumber = editText_main_number.getText().toString();
                editor.putString(mpnumber, mpnumber);
                editor.commit();
                fillListView();
                break;
            case R.id.button_main_clear:
                editor.clear();
                editor.commit();
                fillListView();
                break;
            default:
                break;
        }
    }

    /** 取出 SharedPreferences 中的全部數據,組合成適配器的數據源 */
    private List<String> getBlocklist() {
        List<String> list = new ArrayList<String>();
        try {
            Map<String, ?> map = prefs.getAll();
            for (Map.Entry<String, ?> entry : map.entrySet()) {
                list.add(entry.getKey());
            }
            return list;
        } catch (Exception e) {
            return null;
        }
    }

    /** 刷新 ListView 顯示 */
    private void fillListView() {
        adapter.clear();
        adapter.addAll(getBlocklist());
    }
}

三、內部存儲

Context 類提供了一組文件和目錄處理方法,都是圍繞 /data/data/包名 這個私有空間:

  • getCacheDir():內部緩存目錄 /data/data/包名/cache,應及時清理、節約使用。
  • getFilesDir():內部文件目錄 /data/data/包名/files,注意它和 SharedPreferences 的 /data/data/包名/shared_prefs 不是同一個地方。
  • String[] fileList():列出 files 目錄下的文件。
  • openFileInput(String name):打開 files 目錄下的文件讀取。
  • openFileOutput(String name, int mode):打開內部存儲上的文件寫入,不存在則創建。

四、外部存儲:SDCard 操作

Android 提供了 openFileInput() 和 openFileOutput() 這對專屬方法做 IO,但機內存儲實在有限。要存大文件,就得讀寫 SD 卡。

讀寫 SDCard 的五個步驟

  1. 先判斷有沒有插卡:Environment.getExternalStorageState()。
  2. 獲取路徑:Environment.getExternalStorageDirectory()。
  3. 需要時還可以借助 StatFs 類查可用磁盤空間。
  4. 在清單文件裡申請權限:MOUNT_UNMOUNT_FILESYSTEMS(掛載/卸載,即在 SD 卡中創建與刪除文件)、READ_EXTERNAL_STORAGE(讀)、WRITE_EXTERNAL_STORAGE(寫)。
  5. 執行實際讀寫,就是常規 IO 流操作。

如果想把文件存到特定類型的公共目錄,可以用 Environment.getExternalStoragePublicDirectory(String type),目前支持的類型包括:

  1. DIRECTORY_ALARMS:鬧鈴鈴聲
  2. DIRECTORY_DCIM:相機拍攝的圖片和視頻
  3. DIRECTORY_DOWNLOADS:下載文件
  4. DIRECTORY_MOVIES:電影
  5. DIRECTORY_MUSIC:音樂
  6. DIRECTORY_NOTIFICATIONS:通知音
  7. DIRECTORY_PICTURES:圖片
  8. DIRECTORY_PODCASTS:播客音頻
  9. DIRECTORY_RINGTONES:鈴聲

還有一個常被忽略的問題:多數應用習慣直接在 SD 卡根目錄下建一個文件夾存數據,結果卸載之後垃圾數據還留在卡上。想讓卸載時自動清理,就用下面這兩個目錄:

  • Context.getExternalFilesDir() → SDCard/Android/data/包名/files/,放需要長期保存的數據,對應設置裡的「清除數據 Clear Data」。
  • Context.getExternalCacheDir() → SDCard/Android/data/包名/cache/,放臨時緩存,對應「清除緩存 Clear Cache」。

用這兩個方法的好處是:卸載時 SDCard/Android/data/包名/ 整個目錄會被刪掉,不留垃圾。當然,如果保存的是下載內容(用戶期望卸載後仍在),就不要放這裡。私有 files 目錄下同樣分了 7 種子類型:DIRECTORY_ALARMS、DIRECTORY_MOVIES、DIRECTORY_MUSIC、DIRECTORY_NOTIFICATIONS、DIRECTORY_PICTURES、DIRECTORY_PODCASTS、DIRECTORY_RINGTONES(注意少了 DCIM 和 DOWNLOADS)。

封裝一個 SDCardHelper 工具類

把掛載判斷、空間查詢、各類目錄讀寫都收攏到一個工具類裡,業務代碼會乾淨很多。核心方法如下:

public class SDCardHelper {

    /** 判斷 SD 卡是否已掛載 */
    public static boolean isSDCardMounted() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /** SD 卡根目錄 */
    public static String getSDCardBaseDir() {
        if (isSDCardMounted()) {
            return Environment.getExternalStorageDirectory().getAbsolutePath();
        }
        return null;
    }

    /** 總容量,單位 MB */
    public static long getSDCardSize() {
        if (isSDCardMounted()) {
            StatFs fs = new StatFs(getSDCardBaseDir());
            return (long) fs.getBlockCount() * fs.getBlockSize() / 1024 / 1024;
        }
        return 0;
    }

    /** 剩余空間 */
    public static long getSDCardFreeSize() {
        if (isSDCardMounted()) {
            StatFs fs = new StatFs(getSDCardBaseDir());
            return (long) fs.getFreeBlocks() * fs.getBlockSize() / 1024 / 1024;
        }
        return 0;
    }

    /** 可用空間 */
    public static long getSDCardAvailableSize() {
        if (isSDCardMounted()) {
            StatFs fs = new StatFs(getSDCardBaseDir());
            return (long) fs.getAvailableBlocks() * fs.getBlockSize() / 1024 / 1024;
        }
        return 0;
    }

    /** 寫入 SD 卡公有目錄 */
    public static boolean saveFileToSDCardPublicDir(byte[] data, String type, String fileName) {
        if (!isSDCardMounted()) return false;
        BufferedOutputStream bos = null;
        try {
            File dir = Environment.getExternalStoragePublicDirectory(type);
            bos = new BufferedOutputStream(new FileOutputStream(new File(dir, fileName)));
            bos.write(data);
            bos.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try { if (bos != null) bos.close(); } catch (IOException e) { e.printStackTrace(); }
        }
        return false;
    }

    /** 寫入 SD 卡自定義目錄(不存在則遞歸創建) */
    public static boolean saveFileToSDCardCustomDir(byte[] data, String dir, String fileName) {
        if (!isSDCardMounted()) return false;
        BufferedOutputStream bos = null;
        try {
            File file = new File(getSDCardBaseDir() + File.separator + dir);
            if (!file.exists()) file.mkdirs();
            bos = new BufferedOutputStream(new FileOutputStream(new File(file, fileName)));
            bos.write(data);
            bos.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try { if (bos != null) bos.close(); } catch (IOException e) { e.printStackTrace(); }
        }
        return false;
    }

    /** 寫入私有 files 目錄:SDCard/Android/data/包名/files/ */
    public static boolean saveFileToSDCardPrivateFilesDir(byte[] data, String type,
                                                          String fileName, Context context) {
        if (!isSDCardMounted()) return false;
        BufferedOutputStream bos = null;
        try {
            File dir = context.getExternalFilesDir(type);
            bos = new BufferedOutputStream(new FileOutputStream(new File(dir, fileName)));
            bos.write(data);
            bos.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try { if (bos != null) bos.close(); } catch (IOException e) { e.printStackTrace(); }
        }
        return false;
    }

    /** 寫入私有 cache 目錄 */
    public static boolean saveFileToSDCardPrivateCacheDir(byte[] data, String fileName,
                                                          Context context) {
        if (!isSDCardMounted()) return false;
        BufferedOutputStream bos = null;
        try {
            File dir = context.getExternalCacheDir();
            bos = new BufferedOutputStream(new FileOutputStream(new File(dir, fileName)));
            bos.write(data);
            bos.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try { if (bos != null) bos.close(); } catch (IOException e) { e.printStackTrace(); }
        }
        return false;
    }

    /** 從 SD 卡任意路徑讀文件,返回字節數組 */
    public static byte[] loadFileFromSDCard(String fileDir) {
        BufferedInputStream bis = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            bis = new BufferedInputStream(new FileInputStream(new File(fileDir)));
            byte[] buffer = new byte[8 * 1024];
            int c = 0;
            while ((c = bis.read(buffer)) != -1) {
                baos.write(buffer, 0, c);
                baos.flush();
            }
            return baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                baos.close();
                if (bis != null) bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String getSDCardPublicDir(String type) {
        return Environment.getExternalStoragePublicDirectory(type).toString();
    }

    public static String getSDCardPrivateCacheDir(Context context) {
        return context.getExternalCacheDir().getAbsolutePath();
    }

    public static String getSDCardPrivateFilesDir(Context context, String type) {
        return context.getExternalFilesDir(type).getAbsolutePath();
    }
}

案例:下載網絡圖片存進 SD 卡,再讀出來顯示

點第一個按鈕從網絡拉圖片存盤,點第二個按鈕把剛存的圖讀出來貼到 ImageView 上。網絡請求放在 AsyncTask 裡,避免阻塞主線程:

public class MainActivity extends Activity {
    private ImageView imageView_main_img;
    private String urlString = "https://t2.baidu.com/it/u=2,1891512358&fm=19&gp=0.jpg";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView_main_img = (ImageView) findViewById(R.id.imageView_main_img);
    }

    public void clickButton(View view) {
        switch (view.getId()) {
            case R.id.button_main_save:
                new MyTask(this).execute(urlString);
                break;
            case R.id.button_main_show:
                String filepath = SDCardHelper.getSDCardPath() + File.separator
                        + "mydir" + File.separator + "firstimg.jpg";
                byte[] data = SDCardHelper.loadFileFromSDCard(filepath);
                if (data != null) {
                    Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
                    imageView_main_img.setImageBitmap(bm);
                } else {
                    Toast.makeText(this, "沒有該圖片!", Toast.LENGTH_LONG).show();
                }
                break;
            default:
                break;
        }
    }

    class MyTask extends AsyncTask<String, Void, byte[]> {
        private Context context;
        private ProgressDialog pDialog;

        public MyTask(Context context) {
            this.context = context;
            pDialog = new ProgressDialog(context);
            pDialog.setIcon(R.drawable.ic_launcher);
            pDialog.setMessage("圖片加載中...");
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog.show();
        }

        @Override
        protected byte[] doInBackground(String... params) {
            BufferedInputStream bis = null;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                URL url = new URL(params[0]);
                HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
                httpConn.setDoInput(true);
                httpConn.connect();
                if (httpConn.getResponseCode() == 200) {
                    bis = new BufferedInputStream(httpConn.getInputStream());
                    byte[] buffer = new byte[1024 * 8];
                    int c = 0;
                    while ((c = bis.read(buffer)) != -1) {
                        baos.write(buffer, 0, c);
                        baos.flush();
                    }
                    return baos.toByteArray();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(byte[] result) {
            super.onPostExecute(result);
            if (result == null) {
                Toast.makeText(context, "圖片加載失敗!", Toast.LENGTH_LONG).show();
            } else {
                if (SDCardHelper.saveFileToSDCard(result, "mydir", "firstimg.jpg")) {
                    Toast.makeText(context, "圖片保存OK!", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(context, "圖片保存失敗!", Toast.LENGTH_LONG).show();
                }
            }
            pDialog.dismiss();
        }
    }
}

案例:SDCard 文件浏覽器

原理不複雜:用 File.listFiles() 拿到 File[] 數組,把信息填進 ListView。核心 API 就這幾個:listFiles()、isFile()、isDirectory()、getAbsolutePath()、getParentFile()。

public class MainActivity extends Activity {
    private TextView textView_main_currentpath;
    private ListView listView_main_fileList;
    private File currentFile = null;
    private File[] arrCurrentFiles = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView_main_currentpath = (TextView) findViewById(R.id.text_main_currentpath);
        listView_main_fileList = (ListView) findViewById(R.id.listView_main_filelist);

        if (SDCardHelper.isSDCardMounted()) {
            currentFile = new File(SDCardHelper.getSDCardPath());
            fillListView(currentFile);
        } else {
            Toast.makeText(MainActivity.this, "SDCARD不存在!", Toast.LENGTH_LONG).show();
        }

        listView_main_fileList.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (arrCurrentFiles[position].isDirectory()) {
                    File[] arrSubFiles = arrCurrentFiles[position].listFiles();
                    if (arrSubFiles.length == 0) {
                        Toast.makeText(MainActivity.this, "您點擊的是空目錄!", 2000).show();
                    } else {
                        fillListView(arrCurrentFiles[position]);   // 進入子目錄
                    }
                } else {
                    Toast.makeText(MainActivity.this, "您點擊的不是目錄!", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    public void clickButton(View view) {
        switch (view.getId()) {
            case R.id.imageView_main_back:
                // 已經在根目錄就不再往上跳
                if (!currentFile.getAbsolutePath().equals(SDCardHelper.getSDCardPath())) {
                    fillListView(currentFile.getParentFile());
                }
                break;
            default:
                break;
        }
    }

    public void fillListView(File file) {
        currentFile = file;
        arrCurrentFiles = currentFile.listFiles();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < arrCurrentFiles.length; i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            if (arrCurrentFiles[i].isDirectory()) {
                map.put("imgId", R.drawable.folder);
            } else {
                map.put("imgId", R.drawable.file);
            }
            map.put("filename", arrCurrentFiles[i].getName());
            list.add(map);
        }
        SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, list,
                R.layout.item_listview_main,
                new String[] { "imgId", "filename" },
                new int[] { R.id.imageView_item_listview_type, R.id.text_item_listview_filename });
        listView_main_fileList.setAdapter(adapter);
        textView_main_currentpath.setText(currentFile.getAbsolutePath());
    }
}

最後再提一個同類案例:SDCard 圖片浏覽器。做法和文件浏覽器幾乎一樣,只是把 listFiles() 的結果過濾成圖片文件,再把縮略圖交給適配器渲染即可。

整體來看,Android 的存儲方案選型其實很清晰:輕量的配置項用 SharedPreferences,私有小文件用內部存儲,結構化數據用 SQLite,大文件和需要跨應用共享的公共資源放外部存儲。關鍵是把「私有目錄會隨卸載清理」這件事想清楚,再決定數據到底該落在哪。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved