Search code examples
androidandroid-lifecyclekill-process

Can Android kill my app while it is in the middle of a loop execution?


When Android decides to remove an application from the stack in order to free up some RAM, what happens if the application that is being destroyed is currently running some loop in the background? Will the loop be terminated amid execution or will the VM wait for it to finish?


Solution

  • Will the loop be terminated amid execution or will the VM wait for it to finish?

    The loop is terminated, otherwise it isn't quite "killing".

    Simple test:

    public class MainActivity extends Activity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {
                        Log.i("LOOP", "Running");
                        Thread.sleep(1000);
                    }
                } catch (InterruptedException e) {}
            }
        }).start();
    }
    }
    

    Swipe the app out from the recent apps.