Skip to content Skip to sidebar Skip to footer

Why Does One Background Thread Have The Same Thread Id As The Main Service Thread?

Trying to create 2 background threads and sending a message from thread0 to thread1 where it is handled by MessageHandler using the android Looper and message queue associated wit

Solution 1:

OK, this didn't pop straight up...

the problem is you create the handler within the constructor of the BGThread1 and this code is called from the main thread! and that is why the handler queue is also attached to the main thread.

public BackgroundThread1() {
    super();
    b1Handler = new MessageHandler(); // this is the main thread here...
}

if you want this handler to run on another thread you first have to do something like this:

private class BackgroundThread1 extends HandlerThread {
    public BackgroundThread1() {
        super();
         ...
          Some code
         ...
        start();
        b1Handler = new MessageHandler(getLooper()); 
            // this is the main thread here... but you create the handler with the looper of the new thread!
    }
    ...
}

This would create the thread in the context you expect it to.

===================================================

An example of extending a "regular" thread:

class MyThread
        extends Thread {

    private Handler myHandler;

    public MyThread() {
        start();
    }

    @Override
    public void run() {
        Looper.prepare();
        Looper looper = Looper.myLooper();
        myHandler = new Handler(looper);
        Looper.loop();
    }
}

Now the handler runs on the new thread.


Solution 2:

This is because the Service lifecycle is handled on the main thread, that is : Service methods like onCreate, onStartCommand, onDestruction are called on the main thread by default, as explained in the second paragraph of android.app.Service's Class Overview

Note that services, like other application objects, run in the main thread of their hosting process.


Post a Comment for "Why Does One Background Thread Have The Same Thread Id As The Main Service Thread?"