在應用程式中將個人化的資料儲存,已供下次應用程式啟動時直接使用。
在安卓中使用android.content.SharedPreferences 來儲存設定值。
在安卓中可以透過getSharedPreferences() 方法來存取。
Context context = getActivity();
SharedPreferences spf = context.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
開始建構專案了
首先,在layout 中配置兩個AppCompatEditText與一個button。
接著建立一個Application 類別來處理shareprefrence
在Manifest中 <application>中需指定name =MainApp
<application
android:name=".MainApp"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:requestLegacyExternalStorage="true"
android:theme="@style/Theme.GalaxyFileManage">
Activity 中,先在oncreate 中判斷是否shareprefrence 是否已存有資料,如果有,直接讀取。否則的話在login 過程中將之儲存。
在spf = getSharedPreferences(“my_data.log”,MODE_PRIVATE); 的檔案會被存放在 /data/data/<Package_name>/shared_prefs/ 內