Does the context pass from Activity to the static class this activity forever? Memory leak?

I am trying to create a GCMHelper class. In essence, the class is singleton, and Activity can request a singleton to set GCM () as such.

GCMHelper.getInstance (MainActivity.this) .setupGCM ();

The setupGCM () method will simply see if GCM registration is needed (for example, the application does not have gcm or if the application update needs a new gcm) and do nothing if registration is not required.

This is "normal" because I do not need to touch the value of the GCM identifier. Everything is processed in the setupGCM () singleton method. setupGCM () happens in the background, so control returns to activity. No lag in the user interface. GCM code generation is fast, but I'm trying to explain the following error in the documentation.

public static final String ERROR_SERVICE_NOT_AVAILABLE

The device cannot read the response, or there was 500/503 from the server, which can be repeated later. The application should use exponential shutdown and retry.

So, my setupGCM method will continue to try for now (5 times, to be precise, with several seconds increasing between each delay between each attempt). But what happens if the user clicks and calls finish () for the specified action. Now the action is complete, but the context is still saved using singleton. Is this causing a memory leak ??

This will happen even if GCMHelper is not a single. The reason it is solitary is that the next time an activity is created, it will be able to see if it is still being regenerated.

What happens if I pass it MainActivity.this.getApplicationContext () to the context needed by singleton. Would it be better for Activity because he would be allowed to be GC'd?

+6
source share
1 answer

Yes, you will have a memory leak. You must use the application context. Check out this good article about Context http://possiblemobile.com/2013/06/context/

Quote: If this Context were an Activity, we would effectively hold hostage in memory all the views and other potentially large objects associated with it; creating a leak. If this Context were an Activity, we would effectively hold hostage in memory all the views and other potentially large objects associated with it; creating a leak.

It even has an example for your case using Singleton:

 public class CustomManager { private static CustomManager sInstance; public static CustomManager getInstance(Context context) { if (sInstance == null) { //Always pass in the Application Context sInstance = new CustomManager(context.getApplicationContext()); } return sInstance; } private Context mContext; private CustomManager(Context context) { mContext = context; } } 
0
source

Source: https://habr.com/ru/post/981119/


All Articles