User Settings - Android

2020-03-27 03:29发布

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)?

5条回答
看我几分像从前
2楼-- · 2020-03-27 03:54

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"); 
查看更多
小情绪 Triste *
3楼-- · 2020-03-27 03:57

You need to store these settings within the Database. On how to use this see Using Databases

查看更多
我命由我不由天
4楼-- · 2020-03-27 03:58

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.

查看更多
We Are One
5楼-- · 2020-03-27 03:58

Use SharedPreferences. You can put key value pairs and retrieve when needed .

查看更多
爷、活的狠高调
6楼-- · 2020-03-27 04:00

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);
查看更多
登录 后发表回答