正文  数据库 > Preferences >

Android开发中对SharedPreferences的操作

[代码] [Java]代码 package com.preferences;import android.app.Activity;import android.content.SharedPreferences;import android.os.Bundle;import android.view.KeyEvent;import android.widget.T......

[代码] [Java]代码

 package com.preferences;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.TextView;

public class Activity01 extends Activity {
     private boolean mbMusic = false;
   private TextView mTextView = null;
   private TextView mTextView1 = null;
   private String text = "ni shishui";
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mTextView = (TextView) this.findViewById(R.id.textView1);
        mTextView1 = (TextView) this.findViewById(R.id.textView2);

     //得到当前活动的Preferences 对象
       SharedPreferences settings = getPreferences(Activity.MODE_PRIVATE);

      //取得里面的数据
       mbMusic = settings.getBoolean("bmusic", false);
       text = settings.getString("string", text);
        if(mbMusic)
        {

    //用来显示数据
         mTextView.setText("当前的音乐状态:开");
         mTextView1.setText(text);
         mbMusic = true;
         //mediaPlayer.start();
        }else{
         mTextView.setText("当前音乐状态:关");
          mTextView1.setText(text);
        }
      
    }
    public boolean onKeyUp(int keyCode,KeyEvent event)
    {
     switch(keyCode)
     {

    // 用来改变 mTextView的数据
     case KeyEvent.KEYCODE_DPAD_UP:
      mTextView.setText("当前音乐状态:开");
      mbMusic = true;
      //mediaPlayer.start();
      break;
     case KeyEvent.KEYCODE_DPAD_DOWN:
      mTextView.setText("当前音乐状态:关");
      mbMusic= false;
        // mediaPlayer.stop();
         //mediaPlayer.release();
      break;
     }
     return true;
    }
    public boolean onKeyDown(int keyCode,KeyEvent event)
    {
     if(keyCode == KeyEvent.KEYCODE_BACK){

    // 用来获得当前活动的Preferences
      SharedPreferences State = getPreferences(0);

    //取得编辑对象
      SharedPreferences.Editor editor = State.edit();

     // 编辑string类型的数据
      editor.putString("string", "你爸是**呀?");

     //编辑boolean类型的数据
      editor.putBoolean("bmusic", mbMusic);

     //最后用commit()方法来保存编辑的数据
      editor.commit();
      //结束程序
      this.finish();

//可以不用写return
      return true;
     }

 //这个必须写 但可以写成return true;不受影响
     return super.onKeyDown(keyCode, event);
    }