User Settings - Android

夙愿已清 提交于 2019-12-30 11:11:00

问题


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


来源:https://stackoverflow.com/questions/10346822/user-settings-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!