I have a SyncAdapter overloading onPerformSync. In that method, I'd like to access sharedpreferences to get and put settings. As I understand it, for that I need access to a context. The SyncAdapter onPerformSync has a bundle argument, and maybe I could send the context that way.
In a similar problem, I have another base class (not a service or activity) for which I'm also interested in using sharedPreferences. For this, I would either need to pass the context to a method in the class, or instantiate it with the context that is then saved as a private member.
In both of these cases, I understand that keeping and using a context beyond the lifecycle of the activity or service associated with the context can lead to memory leaks.
In my case, my application can begin with either a broadcastreceiver or the main activity. The broadcast receiver starts a background process, and the main activity just starts the main activity. Whichever opens first registers periodic SyncAdapter updates and opens the other class. So if I were to pass the context of the calling activity or service, what happens if either one of them then closes? The SyncAdapter or base class would use an outdated context, and...memory leak? Or would the context revert to whatever remains running?
I also saw the solution to this: (Static way to get 'Context' on Android?), but would that fix anything? I'd then have an activity context, an application context, and a service context. Same problem right? The SyncAdapter may end up holding on to a context that has closed, no?
Based on the first answer here (SharedPreferences application context vs activity context) I'm tempted to go with the application singleton listed in the previous link, but I want to make sure. Thanks
I think what you want to do is to create a
Service
to manage theSyncAdapter
like mentioned here. That way, theContext
passed to theService
should be valid while theSyncAdapter
is running.The link shows that you would pass
Service.getApplicationContext()
to theSyncAdapter
constructor. Then you could store thatContext
as a field in theSyncAdapter
and use it when you need to. ThatContext
should be valid for as long as you need it.When the app and / or the
SyncAdapter
get GC'd, they should build a newSyncAdapter
with a newContext
the next time you need it.