3

My app uses a Service for background tasks. I want the Service to keep running when user kills the app(swipes it away). There are two scenario's in which the user kan kill the app:

Scenario 1: When in app:
    1 User presses **backbutton**, apps goes to background and user is on the homescreen.
    2 User presses the multitasking button and swips the app away.
    3 The Service should restart because its sticky.

Scenario 2: When in app:
    1 User presses **homebutton**, apps goes to background and user is on the homescreen.
    2 User presses the multitasking button and swips the app away.
    3 The Service should restart because its sticky.

Scenario 1 works exactly as expected. The Service restarts after the app is swiped away in a matter of seconds.

Scenario 2 does not work as expected. The service does get restarted but after more than 5 minutes.

I don't understand why it takes so long to restart the service in scenario 2. Is there a known solution to this?

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent test = new Intent(this, TestService.class);
        startService(test);
    }
}

public class TestService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("Service", "Service is restarted!");//In Scenario 2, it takes more than 5 minutes to print this. 
        return Service.START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
MeesterPatat
  • 2,671
  • 9
  • 31
  • 54

1 Answers1

0

When you press the back button, you are essentially destroying the activity which means the onDestroy() is called where you stop() the STICKY_SERVICE. Hence the STICKY_SERVICE boots up again immediately.

When you press the home button, you are pausing the activity (onPause()), essentially putting it in background. The activity is only destroyed when the OS decides to GC it. It is only at that point of time that the onDestroy() is called at which you stop() the service and STICKY_SERVICE boots up again.

Hope this helps.

user2511882
  • 9,022
  • 10
  • 51
  • 59
  • But when i swipe the app away the onDestroy() is called. No matter in which scenario. In scenario 1 the service gets destroyed and restarts after seconds. In scenario 2 the service gets destroyed and restarts after minutes. This is a problem for me, I need the service to restart within seconds in bot scenario's because the code doesn't run for 5 minutes in scenario 2. – MeesterPatat Apr 25 '15 at 10:37