dfritsi
dfritsi

Reputation: 1232

What happens to Threads started in Android Service when Android restarts the Service?

I have a Service like this (this is not the actual Service, it's just for describing my problem).

public class UploadService {

    private BlockingQueue<UploadData> queue = null;

    private UploadInfoReceiver receiver = null;

    public void onStart(...) {
        queue = new LinkedBlockingQueue<UploadData>();
        (new Processor()).start();
        // creating and reigtering receiver
    }

    public void onDestroy() {
        queue.add(new ServiceDestroyedData());
        // unregistering the receiver
    }

    private class Processor extends Thread() {

        public void run() {
            while (true) {
                UploadData data = queue.take();

                if (data instanceof ServiceDestroyedData) {
                    return;
                }

                // processing data
            }
        }

    }

    private class UploadInfoReceiver extends BroadcastReceiver {

        public void onReceive(Context context, Intent intent) {
            queue.add(new UploadData(/* getting data from intent */));
        }

    }

}

And my problem is that if I do something like this in my App:

if (!isUploadServiceRunning()) {
    // start the Service
}

Then it starts the Service, but when I move my App to the background and open task manager (android 4.2.2), and kill the app, Android restart my Service, and I can see that it creates a whole new instance of it, and I can see that onDestroy never gets called for the previous Service instance. And I also can see that the instance of the previous Processor Thread is no longer running. How can this be? If onDestroy never gets called how does Android know that it should stop my Thread?

Thanks for your answers.

Upvotes: 1

Views: 197

Answers (1)

meredrica
meredrica

Reputation: 2563

Android will kill off anything that it finds that is attached to your apps classloader when you select force stop from the menu. Think kill -9 on Linux. There will be no nice callbacks to any onDestroy methods, the system will just end everything.

Now for your service:

while(true) should really NEVER be used. It will instantly kill the battery and will not do any work 99% of the time anyway.

You area already using a receiver, you can just put your while logic into there and once the upload is done call the next upload and so on. There is absolutely no need for the loop.

Upvotes: 1

Related Questions