1. 程式人生 > >Android資料儲存SharedPreferences的使用場景和注意事項

Android資料儲存SharedPreferences的使用場景和注意事項

Shared Preferences:
       是一種輕量級的儲存,資料會寫在本地的一個xml檔案中,以鍵值對的形式存在!如果程式解除安裝,此檔案也跟著解除安裝!!
       儲存位置:  
                  data/data/程式包名/share_prefs/
      主要用途:
                 1.儲存應用的設定  例如:設定靜音,下次進入還是靜音
                 2.判斷是否是第一次登陸
      使用步驟:
                mode_privatereadable  writeable  writeable
                ShareedPreference sharedPreferences = getSharedPreferencesMODE_PRIVATE
                SharedPreferences.Editor = sharedPreferences.edit();
                寫入:
                獲取sharedPreference:SharedPreferences sharedPreferences = getSharedPreferences(name,mode);
                建立畫筆:Editor edit = sharedPreferences.edit();
                寫資料
                eg:edit.putString("name", "金三胖");
                     edit.putInt("age", 36);
                     edit.putBoolean("hasXF", true);
               提交資料

               edit.commit();

     注意事項:

               配置檔案,強烈建議,要寫成私有模式
              SharedPreferences sharedPreferences = getSharedPreferences(name,MODE_PRIVATE);

Java程式碼詳見如下:(這裡加入了一個上下文選單的效果)

public class MainActivity extends AppCompatActivity {
   private TextView textView;
Handler handler = new 
Handler() { public void handleMessage(android.os.Message msg) { if (msg.what == 0) { // 跟新文字內容 textView.setText(msg.arg1 + ""); } else if (msg.what == 1) { // 進行頁面跳轉 Intent intent = new Intent(); ComponentName componentName = new ComponentName( MainActivity.
this, SecondActivity.class); intent.setComponent(componentName); startActivity(intent); finish(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.iv_01); // 是否是第一次登陸 SharedPreferences sharedPreferences = getSharedPreferences("isOne", MODE_PRIVATE); boolean isOne = sharedPreferences.getBoolean("is", false); if (isOne) { // 登陸過 Intent intent = new Intent(); ComponentName componentName = new ComponentName(MainActivity.this, SecondActivity.class); intent.setComponent(componentName); startActivity(intent); finish(); } else { // 沒有登陸過停留5秒 跳轉到下一頁面Sleep sleep = new Sleep(); Thread thread = new Thread(sleep); thread.start();} } //實現介面的寫法 class Sleep implements Runnable{ @Override public void run() { for (int i = 5; i > 0; i--) { Message msg = new Message(); msg.what = 0; msg.arg1 = i; handler.sendMessage(msg); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 告訴主執行緒,進行頁面跳Message message = new Message(); message.what = 1; handler.sendMessage(message); } } }
一個簡單的Demo演示SharedPreferences的練習.