4
votes

Currently, I have service, which runs in separate process. Here is the code in main activity.

@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 runs in separate process. The reason is that, it will load a large data into memory. Having the service to run in separate process, will allow us to have larger memory limit.
  • Once main activity dead, the service shall dead too.

I was wondering, should I start/stop service in onStart/onStop pairs? Or, shall I start/stop service in onCreate/onDestroy.

The good thing I can think of, when having the code in onStart/onStop pairs is that, I can release unused memory immediately, whenever the activity is invisible. Hence, free up large system resource. Note, onDestroy is not always being called immediately, even the activity has quit.

The bad thing is, if I press HOME and come back frequently, my service will perform memory loading/unloading frequently. This may cause my application performs considerable slower.

1

1 Answers

3
votes

In your scenario you should stop the service onDestroy the reason been is that, its called when the activity is destroyed self, foreclosed or by system when it needs memory. So that will be a appropriate place to end the service.

Where else onStop will be even called when you move back and forth in your application or visit home. The reason onDestroy is not called on home press is the activity is not destroyed yet. Where as if you close activity pressing back it will call onDestroy.