4

I am developing android application which has background running Service.

When I swap out app from the "Recent app List", it will cause the application to shutdown and stop the service. (The following method has the code for the same.)

    @Override
public void onTaskRemoved(Intent rootIntent)
{
       //code to be executed
       //Stop service
       super.onTaskRemoved(rootIntent);
    }

Service start up code is in Application class(onCreate()), it will never be executed if app gets resume.

Positive Scenario

1) If I relaunch app after successful execution of service, new instance of app will be created and service will also start.

Negative Scenario

1) Because there is some code in the above method which is responsible to stop the thread and the service, it causes the app to take some time to stop the service (after swapping from the recent apps). During this time if I relaunch the application, the application resumes instead off getting recreated. Now, the service which was running, will stop.

So,in this type situation I have application but without background service.

How can I handle this situation?

1) Application shouldn't be re-launch until service's task is completed. 2) Start service from launcher activity.

Thanks in advance.

android developer
  • 1,253
  • 2
  • 13
  • 43
Rohan Patel
  • 245
  • 2
  • 10

3 Answers3

0

in onStartCommand() of Service class , You have to set return as "START_STICKY" that ensure restart service which is terminated by android platform(if app breaks).

0

You can check the status of the service in OnResume and restart from there using Intent

  @Override
    protected void onResume() 
    {
        /*   This will be called when starting the UI and resume from background
         *   If the service is not running, then start the service and bind to the service. 
         *   If the service is already running, then just bind with the service. The status
         *   of the service is determined by the #DetermineServiceStatus function.
         */


      }
DAC84
  • 421
  • 1
  • 8
  • 20
0

You have almost no control over service' s lifetime. Background services are prone to be killed by Android, whenever system needs more resources.

The best way to design a background service is return a START_STICKY from your onStartCommand() (which you already did) to ensure that when enough resources become available, your service automatically be restarted, and the job that you perform within the background service should be implemented so that even if it is interrupted, it should succesfully continue its task when restarted by Android OS.

Alpay
  • 1,350
  • 2
  • 24
  • 56