使用 Preference 讀寫資料相當簡單。
PreferenceActivity
public class PreferenceActivity extends Activity { private static final String TAG = "PreferenceActivity"; private static final String CURRENT_KEY = "MAX"; private static final int MAX = 30; private CountDownHandler handler; private TextView tv; @Override public void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate..."); super.onCreate(savedInstanceState); setContentView(R.layout.main); this.handler = new CountDownHandler(); this.tv = (TextView) this.findViewById(R.id.tv); } @Override protected void onResume() { Log.d(TAG, "onResume..."); super.onResume(); // 從 Preference 裡讀取上次保留的值,如果沒有就用預設值 SharedPreferences pref = this.getPreferences(MODE_PRIVATE); int current = pref.getInt(PreferenceActivity.CURRENT_KEY, PreferenceActivity.MAX); Log.d(TAG, "Get the current from preference..." + current); this.handler.current = current; this.handler.pause = false; this.handler.sendEmptyMessage(0); } @Override protected void onPause() { Log.d(TAG, "onPause..."); super.onPause(); this.handler.pause = true; // 程式暫停,將目前的值寫到 Preference SharedPreferences pref = this.getPreferences(MODE_PRIVATE); Editor editor = pref.edit(); editor.putInt(PreferenceActivity.CURRENT_KEY, this.handler.current); // 一定要 commit editor.commit(); Log.d(TAG, "Put the current to preference..." + this.handler.current); } public void show(int max) { this.tv.setText(String.valueOf(max)); } public void reset(View view) { Log.d(TAG, "reset..."); int cur = this.handler.current; this.handler.current = PreferenceActivity.MAX; if (cur == 0) { this.handler.sendEmptyMessage(0); } } private final class CountDownHandler extends Handler { private boolean pause; private int current; public CountDownHandler() { Log.d(TAG, "new a CountDownHandler..."); } @Override public void handleMessage(Message msg) { Log.d(TAG, "handleMessage..." + this.current); if (this.pause) { Log.d(TAG, "paused!"); return; } if (this.current == 0) { Log.d(TAG, "finished!"); return; } this.current--; show(this.current); this.sendMessageDelayed(this.obtainMessage(), 1000); } } }main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/tv" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btn" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Reset" android:onClick="reset" /> </LinearLayout>
沒有留言:
張貼留言