0

I have an activity where I have two threads running off the Main thread. Both of access network and Shared Preferences. And the context I use for them is application context. So, is it recommended to use a single application context instance (maybe static?), member of the main activity, initialized in onCreate; for accessing, editing Shared Preferences from Multiple threads?

emotionull
  • 595
  • 2
  • 8
  • 24

1 Answers1

2

There can be no memory leak with the application context, so it can be safely stored in a static member. Be mindful, however, that this context should not be used to create View instances (but it's OK for SharedPreferences).

If you launch the threads from an Activity instance, you can simply use getApplicationContext().

Another common way is to subclass Application, then store the reference to the object in a static field. For example:

public class MyApplication extends Application
{
    static sApplication;

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

    public static Context getAppContext()
    {
        return sApplication.getApplicationContext();
    }

    ...
}
matiash
  • 54,791
  • 16
  • 125
  • 154
  • Ok. I guess then using `getApplicationContext()` would be better. Also, if I make the `SharedPreference` object an instance of activity and use it across threads, would that be better? – emotionull Jun 20 '14 at 18:22
  • `SharedPreferences` implementation is thread-safe (at least according to http://stackoverflow.com/a/4695567/82788) so that would work. – matiash Jun 20 '14 at 18:32