Should I start / stop the service in onStart / onStop or onCreate / onDestroy

I currently have a service that runs in a separate process. Here is the code in the main action.

@Override public void onStart() { super.onStart(); // Start auto complete service. autoCompleteServiceIntent = new Intent(AutoCompleteService.class.getName()); startService(autoCompleteServiceIntent); bindService(autoCompleteServiceIntent, serviceConnection, 0); } @Override public void onStop() { super.onStop(); // Stop auto complete service. unbindService(serviceConnection); stopService(autoCompleteServiceIntent); autoCompleteServiceIntent = null; } 

The service will have the following characteristics.

  • The service starts in a separate process. The reason is that it will load big data into memory. Having a service to run in a separate process will allow us to have a larger memory limit.
  • Once the main action is dead, the service will also be dead.

I was wondering whether to start / stop the service in onStart / onStop pairs ? Or, I have to start / stop the service in onCreate / onDestroy .

It’s good that I can think of it when the code in onStart / onStop pairs is like this, I can immediately free up unused memory, whenever activity is invisible. Therefore, free up a large system resource. Please note: onDestroy is not always called immediately, even activity is stopped.

It is bad if I press HOME and return often, my service will often load / unload memory. This can lead to a significant slowdown in my application.

+4
source share
1 answer

In your scenario, you must stop the onDestroy service, the reason is that it is called when the action is destroyed on its own, excluded, or by the system when it needs memory. Thus, it will be a suitable place to complete the service.

Where else onStop will be called even when you move back or forward in your application or visit a house. The reason onDestroy is not called in the home press - this action has not yet been destroyed. Wherever you close an activity by clicking on it, onDestroy is called .

+3
source

All Articles