Android學習筆記(13)————利用SharedPreferences來儲存應用程式的資料

來源:互聯網
上載者:User

/********************************************************************************************
 * author:conowen@大鐘                                                                                                                          
 * E-mail:conowen@hotmail.com                                                                                                             
 * http://blog.csdn.net/conowen                                                                                                              
 * 註:本文為原創,僅作為學習交流使用,轉載請標明作者及出處。     

 ********************************************************************************************/

1、SharedPreferences的簡單介紹

        應用程式在啟動並執行時候,可能會隨著使用者的使用而保持該使用者的配置資訊,如上次播放時的eq設定,音量設定,上網的cookies資訊等等,這些小量 的資訊可以通過SharedPreferences來保持,通過SharedPreferences保持的資料為一個XML檔案,位於應用程式的私人檔案夾。

2、具體操作方法

擷取SharedPreferences,可以通過以下方法擷取

public
SharedPreferences getSharedPreferences
(String name, int mode)Since: API Level 1

Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they
will see each other's edits as soon as they are made.

Parameters
name Desired preferences file. If a preferences file by this name does not exist, it will be created when you retrieve an editor (SharedPreferences.edit()) and then commit changes (Editor.commit()).
mode Operating mode. Use 0 or MODE_PRIVATE for the default operation,MODE_WORLD_READABLE
andMODE_WORLD_WRITEABLE to control permissions. The bitMODE_MULTI_PROCESS
can also be used if multiple processes are mutating the same SharedPreferences file.MODE_MULTI_PROCESS is always on in apps targetting Gingerbread (Android 2.3) and
below, and off by default in later versions.
Returns
  • Returns the single SharedPreferences instance that can be used to retrieve and modify the preference values.

 

參數簡述:

Name————獲得SharedPreferences之後,將會在應用程式的私人檔案夾中儲存著一個XML檔案,第一個參數name就是這個檔案名稱字。

Mode————XML檔案的儲存模式,預設為0,也就是MODE_PRIVATE

 

3、簡單的demo

通過service的一個音樂播放例子,“播放”與“暫停”兩個按鈕

暫停之後,保持播放進度到SharedPreferences裡面,然後再次播放的話,讀取進度值進行音樂播放。

/* * @author:conowen * @date:12.3.01 *  */package com.conowen.sharedpreferences;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class SharedPreferencesActivity extends Activity {    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        Button play = (Button) findViewById(R.id.play);          Button pause = (Button) findViewById(R.id.pause);           final Intent intent = new Intent(SharedPreferencesActivity.this,service.class);          // 定義intent為final,全域變數,供下面兩個匿名內部類(onclicklisenter)使用          play.setOnClickListener(new OnClickListener() {                @Override              public void onClick(View v) {                  // TODO Auto-generated method stub                  startService(intent);                  // 開始播放,通過前面定義好的intent傳遞                }          });          pause.setOnClickListener(new OnClickListener() {                @Override              public void onClick(View v) {                  // TODO Auto-generated method stub                  stopService(intent);                  // 停止播放                }          });              }}

 

第二個class是繼承service的,記得在manifest.XML裡面註冊service

 

/* * @author:conowen * @date:12.3.01 *  */package com.conowen.sharedpreferences;import android.app.Service;import android.content.Intent;import android.content.SharedPreferences;import android.media.MediaPlayer;import android.os.IBinder;public class service extends Service {MediaPlayer player;// 建立播放器@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();player = MediaPlayer.create(this, R.raw.lt26);player.setLooping(true);// 兩種方式的第一個生命週期都是onCreate()}@Overridepublic void onStart(Intent intent, int startId) {// TODO Auto-generated method stubsuper.onStart(intent, startId);SharedPreferences sp = this.getSharedPreferences("music_progress",MODE_PRIVATE);// music_progress為XML檔案的檔案名稱player.seekTo(sp.getInt("progress", 0));// progress為索引值對中的key,progress所對應的值通過player.getCurrentPosition()獲得,請看下面詳細// 每次調用onStart方法時,就會設定player的進度// MediaPlayer的seekTo方法,讀取進度,然後播放,getInt的第一個參數是所要讀取的key名字,第二個參數為預設初始值。也就是說進度初始預設為0player.start();}@Overridepublic void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();SharedPreferences sp = this.getSharedPreferences("music_progress",MODE_PRIVATE);sp.edit().putInt("progress", player.getCurrentPosition()).commit();// player.getCurrentPosition()方法擷取播放進度的資料// commit()方法是儲存SharedPreferences擷取來的資料player.stop();}@Overridepublic IBinder onBind(Intent intent) {// TODO Auto-generated method stubreturn null;}}

通過SharedPreferences儲存的文檔如下所示,開啟DDMS,切換到File Explore,在私人目錄下的shared_prefs檔案夾裡面,路徑為

/data/data/你的包名/shared_prefs

內容如下

<?xml version='1.0' encoding='utf-8' standalone='yes' ?><map><int name="progress" value="90695" /></map>


關於service的詳細內容,可以參考之前的博文

http://blog.csdn.net/conowen/article/details/7272018

 

聯繫我們

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