Just make sure you pass context.getApplicationContext () or call getApplicationContext () in any context that is passed through the methods / constructor to your singleton if you decide to save it in any member field.
An example of an idiot proof (even if someone passes it into action, it will capture the application context and use it to instantiate the single):
public static synchronized RestClient getInstance(Context context) { if (mInstance == null) { mInstance = new RestClient(context.getApplicationContext()); } return mInstance; }
getApplicationContext () according to the docs: "Return the context of a single global application object of the current process."
This means that the context returned by getApplicationContext () will go through the whole process, and therefore it doesnβt matter if you store a static link to it anywhere, because it will always be present at the time your application is running (and survive any objects / singles created by him).
Compare this with the context inside representations / activities containing large amounts of data, if you are running a context occupied by activity, the system will not be able to free this resource, which is clearly not suitable.
A link to an activity according to its context should live in the same life cycle as the activity itself, otherwise it will keep the context hostage causing a memory leak (which is the reason for the lint warning).
EDIT: For the guy who is beating up an example from the above documents, there is even a comment section in the code about what I just wrote:
// getApplicationContext() is key, it keeps you from leaking the // Activity or BroadcastReceiver if someone passes one in.
Marcus Gruneau Oct 25 '16 at 9:08 2016-10-25 09:08
source share