How to make in app changes persist so that when app relaunches all settings remain same(like if from app i have selected vibration then when app is not running if my phone is ringer mode when app relaunches it sets itself to vibration)?
问题:
回答1:
There's actually multiple ways to persist changes. The Android documentation covers all of them in more detail, but essentially these are the five ways. Easiest is SharedPreferences
, probably.
Shared Preferences
Store private primitive data in key-value pairs.
Internal Storage
Store private data on the device memory.
External Storage
Store public data on the shared external storage.
SQLite Databases
Store structured data in a private database.
Network Connection
Store data on the web with your own network server.
回答2:
Use SharedPreferences. You can put key value pairs and retrieve when needed .
回答3:
You need to store these settings within the Database. On how to use this see Using Databases
回答4:
Use SharedPreferences
Save your settings:
SharedPreferences prefs = getSharedPreferences("myprefs",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("email", "my_email@email.com");
editor.putString("name", "Albert");
editor.commit();
Retrieve them:
SharedPreferences prefs = getSharedPreferences("myprefs",Context.MODE_PRIVATE);
String email = prefs.getString("email", "default@email.com");
回答5:
Thing that you could do is to create a PreferenceActivity like :
public class Prefs extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
}
}
In res/xml folder add preference.xml with this content :
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="General" >
<CheckBoxPreference
android:key="notification"
android:summaryOff="You will not receive any notification"
android:summaryOn="Notifications are sent to your device"
android:title="Get notification" />
</PreferenceCategory>
</PreferenceScreen>
In your code you can do now :
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
Boolean sendNotification = prefs.getBoolean("notification", false);