android開發中SharedPreferences用法詳解(含原始碼和運行結果截圖),android原始碼

來源:互聯網
上載者:User

android開發中SharedPreferences用法詳解(含原始碼和運行結果),android原始碼

      在Android應用程式開發中,經常需要儲存一些類似於配置資訊的簡單類型資料,比如遊戲玩家的積分、是否開啟音效等。SharedPreferences類為我們儲存、讀取這些資料提供了便利。

      SharedPreferences介面提供以下常用方法來訪問SharedPreferences對象中的key-value對:

      boolean contains(String key):判斷SharedPreferences對象是否包含鍵值為key的資料。

      boolean getXxx(String key, xxx defaultValue):擷取SharedPreferences對象中指定key對應的value。如果該key不存在,返回預設值defaultValue。xxx可以是boolean、float、int、String、long等基本類型。

     調用SharedPreferences的edit()方法可以獲得Editor對象,通過Editor對象來向SharedPreferences對象中寫入資料,有以下常用方法:

      SharedPreferences prefs;

      Editor editor = prefs.edit();

      editor.clear():清空資料

      editor.putXxx(String key, xxx value):向SharedPreferences對象中存入指定key對應的資料,xxx可以是boolean、float、int、String、long等基本類型。

      editor.remove(String key):刪除key對應的資料

      editor.apply():儲存更改,用於Android 2.3以上版本,非同步寫入,安全執行緒。

      editor.commit():儲存更改,同步寫入,它會阻塞調用線程,寫入成功返回true,寫入失敗返回false。

      SharedPreferences是一個介面,只能通過Context提供的getSharedPreferences(String  name, int  mode)方法來擷取執行個體。mode參數支援以下幾個值:

        Context.MODE_PRIVATE:只能被本應用程式讀寫。

        Context.MODE_WORLD_READABLE:能被其他應用程式唯讀。

        Context.MODE_WORLD_WRITEABLE:能被其他應用程式讀、寫。

       SharedPreferences儲存的資料在程式重啟後仍然有效,所以可以用來儲存使用者佈建的一些資料。

        下面來看我的一個demo,在一個activity中點“設定”按鈕跳轉到另一個activity中,設定相關選項後,重啟應用程式,則可以在activity中看到上次設定的結果。

       主activity布局xml代碼:

<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >        <Button        android:id="@+id/setButton"         android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="設定"        android:textSize="20dp"/>        <LinearLayout         android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal">                 <TextView             android:id="@+id/engineLabel"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="識別引擎:"            android:textSize="20dp"/>                <TextView             android:id="@+id/engineTextView"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:textSize="20dp"/>    </LinearLayout>       <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal">                <TextView             android:id="@+id/languageLabel"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="識別語言:"            android:textSize="20dp"/>            <TextView             android:id="@+id/languageTextView"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:textSize="20dp"/>    </LinearLayout>    </LinearLayout></span>

       主activity的java代碼:

<span style="font-size:18px;">package my.set;import my.set.R;import android.app.Activity;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class TestActivity extends Activity{TextView engineView;TextView languageView;Button setButton;SharedPreferences sharedPreferences;class buttonListener implements OnClickListener {public void onClick(View view) {Intent intent = new Intent(TestActivity.this, SetActivity.class);startActivity(intent);}}@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);engineView = (TextView)findViewById(R.id.engineTextView);languageView = (TextView)findViewById(R.id.languageTextView);setButton = (Button)findViewById(R.id.setButton);sharedPreferences = getSharedPreferences("set", MODE_PRIVATE);String engineString = sharedPreferences.getString(SetActivity.PREF_OCR_ENGINE, "");String languageString = sharedPreferences.getString(SetActivity.PREF_RECOGNIZED_LANGUAGE, "");setButton.setOnClickListener(new buttonListener());engineView.setText(engineString);languageView.setText(languageString);        }}</span>

       設定介面的xml布局代碼:

<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <TextView         android:id="@+id/engine_text_view"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="@string/engine_text_view"        android:textSize="20dp"/>        <RadioGroup         android:id="@+id/engine_radio_group"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:orientation="vertical">                <RadioButton             android:id="@+id/tesseract_radio_button"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@string/tesseract_radio_button"            android:textSize="20dp"/>                <RadioButton             android:id="@+id/tesseract_and_cube_radio_button"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@string/tesseract_and_cube_radio_button"            android:textSize="20dp"/>    </RadioGroup>             <TextView          android:id="@+id/language_text_view"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="@string/language_text_view"        android:textSize="20dp"/>        <RadioGroup         android:id="@+id/language_radio_group"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="vertical">                <RadioButton             android:id="@+id/Chinese_radio_button"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@string/Chinese_radio_button"            android:textSize="20dp"/>                <RadioButton             android:id="@+id/Engilsh_radio_button"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@string/English_radio_button"            android:textSize="20dp"/>    </RadioGroup>        <LinearLayout         android:orientation="horizontal"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:gravity="center_horizontal">                <Button             android:id="@+id/okButton"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@string/ok"            android:textSize="20dp"/>                <Button             android:id="@+id/cancelButton"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@string/cancel"            android:textSize="20dp"/>    </LinearLayout></LinearLayout></span>

      設定介面的java代碼:

<span style="font-size:18px;">package my.set;import android.app.Activity;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.RadioButton;import android.widget.RadioGroup;import my.set.R;public class SetActivity extends Activity {//定義識別引擎的選項按鈕RadioButton tesseractRadioButton;RadioButton tessAndCubeRadioButton;//定義識別語言的選項按鈕RadioButton chineseRadioButton;RadioButton englishRadioButton;RadioGroup engineGroup;RadioGroup languageGroup;Button okButton;Button cancelButton;public static final String PREF_OCR_ENGINE = "PREF_OCR_ENGINE";public static final String PREF_RECOGNIZED_LANGUAGE = "PREF_RECOGNIZED_LANGUAGE";SharedPreferences prefs;private String choosedEngine = "";private String choosedLanguage = "";@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.set);tesseractRadioButton = (RadioButton)findViewById(R.id.tesseract_radio_button);tessAndCubeRadioButton = (RadioButton)findViewById(R.id.tesseract_and_cube_radio_button);chineseRadioButton = (RadioButton)findViewById(R.id.Chinese_radio_button);englishRadioButton = (RadioButton)findViewById(R.id.Engilsh_radio_button);engineGroup = (RadioGroup)findViewById(R.id.engine_radio_group);languageGroup = (RadioGroup)findViewById(R.id.language_radio_group);okButton = (Button)findViewById(R.id.okButton);cancelButton = (Button)findViewById(R.id.cancelButton);prefs = getSharedPreferences("set", MODE_PRIVATE);//添加事件監聽器engineGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(RadioGroup group, int checkedId) {// TODO Auto-generated method stubif (checkedId == R.id.tesseract_radio_button) {choosedEngine = tesseractRadioButton.getText().toString();} else {choosedEngine = tessAndCubeRadioButton.getText().toString();}}});languageGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(RadioGroup group, int checkedId) {// TODO Auto-generated method stubif (checkedId == R.id.Chinese_radio_button) {choosedLanguage = chineseRadioButton.getText().toString();} else {choosedLanguage = englishRadioButton.getText().toString();}}});okButton.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubsavePreferences();finish();}});cancelButton.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubfinish();}});}private void savePreferences() {Editor editor = prefs.edit();editor.putString(PREF_OCR_ENGINE, choosedEngine);editor.putString(PREF_RECOGNIZED_LANGUAGE, choosedLanguage);editor.commit();}}</span>
下面是:

       第一次啟動後介面:



      設定介面:


  點擊儲存按鈕後,重啟應用程式,則看到上次設定結果如:


     開啟DDMS的File Explorer,SharedPreferences資料儲存在/data/data/<package name>/shared_prefs檔案夾下,如:


      匯出這個xml檔案,開啟如:


聯繫我們

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