Android 資料存放區——shared preferences

來源:互聯網
上載者:User

1.使用getPreferences方法建立檔案的模式
        檔案建立模式:Activity.MODE_APPEND
        如果該檔案已經存在,然後將資料寫入,而不是抹掉它現有檔案的末尾。
       
        檔案建立模式:MODE_PRIVATE
        預設模式,在那裡建立的檔案只能由應用程式調用,即為私人的
       
        檔案建立模式:Activity.MODE_WORLD_READABLE
        允許所有其他應用程式有讀取和建立檔案的許可權。
       
        檔案建立模式:Activity.MODE_WORLD_WRITEABLE
        允許所有其他應用程式具有寫入、訪問和建立的檔案許可權。
2.儲存SharedPreferences配置值
                        SharedPreferences uiState = getPreferences(0);
                        // 取得編輯對象
                        SharedPreferences.Editor editor = uiState.edit();
              // 添加值
              editor.putBoolean("bmusic", mbMusic);
              editor.putFloat("argFloat", 1f);
              editor.putInt("argInet", 2);
              editor.putLong("argLong", 1313);
              editor.putString("argStr", "string");
3.清除SharedPreferences配置值
        清除所有值:editor.clear();
        清除某一項值:editor.remove("argStr");
4.提交修改值
        editor.commit();
        editor.clear();
5.擷取SharedPreferences配置值
        SharedPreferences settings = getPreferences(Activity.MODE_PRIVATE);
        mbMusic = settings.getBoolean("bmusic", false);
6.添加配置變更監聽器
        當多個應用共用配置時,可以添加配置變更監聽器,監聽配置是否發生變化
                        settings.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {                       
                        @Override
                        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
                                System.out.println("onSharedPreferenceChanged");
                        }
                });
7.查看SharedPreferences設定檔:
如android應用開發揭秘中對應的設定檔就在下面目錄位置:

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.