Android - using Singleton to access hold application settings, and Context

ぃ、小莉子 提交于 2019-12-08 03:26:04

问题


I need to access settings from various activities in my Android app. Rather than messing around with SharedPreferences in various activities I want to create a Singleton class, and grab all the settings at once using SharedPreferences in the Singleton. I also want a method in the Singleton to save settings where required, again using SharedPreferences.

The trouble with this is that I need an Activity context to use SharedPreferences. Could I pass this into the Singleton.. I've read about memory leaks and am wary of doing this.

Or am I completely barking up the wrong tree and is there a better way of sharing application settings between activities?


回答1:


As far as sharing information between Activities, you pretty much have two options:

  1. Singleton Class, like you suggested.
  2. Extend the Application class and store your information there (which to my limited knowledge, is some sort of buffed Singleton).

Personally I use Singletons to manage Application Scoped Information in my Android applications. I'd like to give you the pros and cons to both approach myself but it's been debated heavily all over the internet ;) This question answered all my question when I got into Android programming and was trying to figure out how to shared information in my application in the most intelligent way possible.

I, personally never had any problems passing my Context to Singletons in order for them to do work related to Shared Preferences. I guess you've just have to be careful about what you're doing, like anything you're coding really.




回答2:


You can try:

public class SomeApplication extends Application {


    private static SomeApplication _instance;

    public SomeApplication() {
       super();
    }

    public static SomeApplication getInstance() {
       return _instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();  
        _instance = this;
    }

    public SharedPreferences getPreferences() {
         return getApplicationContext().getSharedPreferences( SOME_PREFS_KEY, Context.MODE_PRIVATE );
    }

}

    .....
       SharedPreferences prefs =  SomeApplication.getInstance().getPreferences();
    ..... 

Don't forget about manifest.xml

    <application android:label="@string/app_name" android:icon="@drawable/icon"
             android:name="SomeApplication"
       >


来源:https://stackoverflow.com/questions/9471645/android-using-singleton-to-access-hold-application-settings-and-context

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