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

Android 學習:SharedPreferences 輕量資料持久化實作

編輯:關於 Android 程式設計

SharedPreferences 是 Android 提供的輕量級資料儲存機制,適合保存設定、狀態等鍵值對資料。本例以一個音樂開關狀態的保存與還原為例,示範其用法。

執行效果圖:

本專案在 config.xml 中定義字串資源,並包含 MainActivity.java、MIDIPlayer.java 與 activity_main.xml。透過方向鍵上/下切換音樂狀態,退出應用時將狀態存入 SharedPreferences,下次啟動時再讀回並還原。

MainActivity.java

package com.example.l3_sharedpreferences;

import com.example.l3_sharedpreferences.model.MIDIPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.KeyEvent;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {
    private TextView musicStateShow;
    private MIDIPlayer midiPlayer;
    private boolean musicSate = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        musicStateShow = (TextView) this.findViewById(R.id.musicStateShow);
        midiPlayer = new MIDIPlayer(this);
        SharedPreferences sharedPreferences = getSharedPreferences("music", MODE_PRIVATE);
        musicSate = sharedPreferences.getBoolean("mState", false);
        if (musicSate) {
            musicStateShow.setText("當前音樂狀態:開");
            midiPlayer.playMusic();
        } else {
            musicStateShow.setText("當前音樂狀態:關");
        }
    }

    /** 按鍵彈起事件 */
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_UP:
                musicStateShow.setText("當前音樂狀態:開");
                musicSate = true;
                midiPlayer.playMusic();
                break;
            case KeyEvent.KEYCODE_DPAD_DOWN:
                musicStateShow.setText("當前音樂狀態:關");
                musicSate = false;
                midiPlayer.freeMusic();
                break;
            default:
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    /** 按鍵按下事件 */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 退出應用程式時保存資料
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            SharedPreferences sharedPreferences = getSharedPreferences("music", MODE_PRIVATE);
            Editor editor = sharedPreferences.edit();
            editor.putBoolean("mState", musicSate);  // 寫入資料
            editor.commit();                          // 提交保存
            if (musicSate) {
                midiPlayer.freeMusic();
            }
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

MIDIPlayer.java

package com.example.l3_sharedpreferences.model;

import java.io.IOException;
import com.example.l3_sharedpreferences.R;
import android.content.Context;
import android.media.MediaPlayer;

public class MIDIPlayer {
    public MediaPlayer playerMusic = null;
    private Context mContext = null;

    public MIDIPlayer(Context context) {
        mContext = context;
    }

    /** 播放音樂 */
    public void playMusic() {
        playerMusic = MediaPlayer.create(mContext, R.raw.start);  // 載入資源中的音樂
        playerMusic.setLooping(true);                             // 設定循環播放
        try {
            playerMusic.prepare();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        playerMusic.start();
    }

    /** 停止並釋放音樂 */
    public void freeMusic() {
        if (playerMusic != null) {
            playerMusic.stop();
            playerMusic.release();
        }
    }
}

activity_main.xml

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <TextView android:id="@+id/musicStateShow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/currentMusic"/>
</RelativeLayout>

透過 getSharedPreferences 取得 editor,再以 putBoolean 與 commit 完成寫入;下次啟動時用 getBoolean 讀回,即可實現狀態的持久化保存。

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