Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly happens when you remove a task from recents?

Tags:

android

I noticed a surprising behavior when removing an app from the app switcher by swiping. The app has a service. When the app is "killed", any threads started from the service keep running, other threads are terminated.

What's really surprising is that the system can determine which threads were started from the service, even if I try to obfuscate the thread's origin like this:

  • In the service's onCreate() method, post a runnable to the main thread handler.
  • The runnable starts a new thread which survives removal from recents.

If I post the exact same runnable to the exact same handler but from an activity, the thread doesn't survive. How can the system possibly know? Does it somehow track which thread was the runnable posted from?

Edit: As requested, the onCreate() method:

@Override
public void onCreate() {
    super.onCreate();

    new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
        @Override
        public void run() {
            new Thread(){
                @Override
                public void run() {
                    while (true) {
                        System.out.println("hello from thread");
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            }.start();
        }
    }, 1000);
}
like image 944
fhucho Avatar asked Oct 19 '22 02:10

fhucho


1 Answers

Finally found out what happens. The system doesn't selectively kill non-service threads, it kills the whole app and then starts the service again, so it appears that the service's threads were untouched.

like image 106
fhucho Avatar answered Oct 21 '22 05:10

fhucho