My application consists of Activity and Service. The service does the main work (transfers data in the background to the server), the Activity is used to manage the service.

Initially, the Activity is started, the service is started in it:

@Override public void onResume() { super.onResume(); startService(new Intent(this, LocService.class)); } 

Then you can close the Activity, leave the service to work, or completely close the application (with the service stopped).

The service creates a tray notification. Activation can be reopened via the tray or the icon on the desktop.

So, when you reopen the Activity, the memory consumed by the application is constantly increasing. Of course, this can also be a normal process, and then the garbage collector will remove it, and maybe a leak.

I see possible memory leaks:

  1. When creating a service. Every time an Activity is created, a new instance of the service is launched? But on the other hand a one-time call

    stopService (new Intent (this, LocService.class)); kills service.

  2. When you start the activation, a new instance is created each time, and memory allocation is inevitable. It remains to hope for the scavenger that he will clean everything.

PS: Starting Activity through Notification happens with flags

 Intent intent = new Intent(this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | intent.FLAG_ACTIVITY_SINGLE_TOP); 

otherwise, a second instance of the Activity was created and exit from it using the Back button led to the previous instance of the Activity. Now everything is correct.

1 answer 1

If I understand correctly, I can advise this:

1) start the service in onCreate , and not in onResume , because if you minimize the application and re-enter, then onResume will be called again, while onCreate is called only once. Read about the life cycle of the activity.

2) make the service check something like this:

  if (сервис не запущеный) { запусти сервис) } 

Google this topic, on the first link there is a good answer.

3) check if you accidentally destroy the service when exiting the appliance