问题
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 informations periodically (1 second)
- Get GPS Location periodically (1 second)
- Write previous datas in a text file every 1 second
For this, I created from my remote service 2 Threads : one for the data request (loopThread) and one for the GPS Location (gpsThread). The loopThread, after getting the datas from the blueTooth Device should ask the gpsThread for the location. It has to be very quick, that's why I am using a Thread, so i can store the Location in a variable which can be sent.
The remote serviceand the 2 threads should communicate through handlers.
The problem is : I can make each Handlers communicate with the remote service, but not with each other.
I create Threads like this :
myGPSThread = new GPSThread(mainServiceHandler,locationManager);
myLoopThread = new AcquisitionThread(mainServiceHandler, sockIn, sockOut);
I tried sending the Handler of one to the other by message, but Handlers seem not to be parcelable.
Does anyone have the solution to this?
回答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.
final class GPSThread extends HandlerThread implements Handler.Callback {
private Handler otherThreadHandler;
public void setOtherThreadHandler(Handler otherThreadHandler) {
this.otherThreadHandler = otherThreadHandler;
}
@Override
public void handleMessage(Message msg) {
// like in your comment
}
}
myGPSThread = new GPSThread(locationManager);
myLoopThread = new AcquisitionThread(sockIn, sockOut);
myGPSThreadHandler = new Handler(myGPSThread.getLooper(), myGPSThread);
myLoopThreadHandler = new Handler(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.
来源:https://stackoverflow.com/questions/16010607/how-to-initialize-handlers-from-separated-threads