Skip to content Skip to sidebar Skip to footer

How To Initialize Handlers From Separated Threads?

I am coding an application where a remote service has to run at all time and to perform these taks : Create and keep a bluetooth connection to another device Ask this device for i

Solution 1:

If you want to stick to your Handler based approach, you can set up your two Threads as follows.

For your Threads, subclass HandlerThread instead of Thread. Also, make them implement Handler.Callback and don't start() them right away.

finalclassGPSThreadextendsHandlerThreadimplementsHandler.Callback {
    private Handler otherThreadHandler;
    publicvoidsetOtherThreadHandler(Handler otherThreadHandler) {
        this.otherThreadHandler = otherThreadHandler;
    }
    @OverridepublicvoidhandleMessage(Message msg) {
        // like in your comment
    }

}

myGPSThread  = newGPSThread(locationManager);
myLoopThread = newAcquisitionThread(sockIn, sockOut);
myGPSThreadHandler  = newHandler(myGPSThread.getLooper(), myGPSThread);
myLoopThreadHandler = newHandler(myLoopThread.getLooper(), myLoopThread);
myGPSThread.setOtherThreadHandler(myLoopThreadHandler);
myLoopThread.setOtherThreadHandler(myGPSThreadHanlder);
myGPSThread.start();
myLoopThread.start();

If you want low latency and your event-driven code is short and friendly, you may want to create the HandlerThreads with a better-than-default priority; see here.

As already mentioned, you can as well set up two "ordinary" Threads which operate on two LinkedBlockingQueues; these Threads would block in their run() methods upon waiting for a message (aka Object) from the other Thread.

Post a Comment for "How To Initialize Handlers From Separated Threads?"