Reputation: 323
need your help again : I am using the bluetooth chat example by android and try to implement a function which waits for the answer from the handler :
public void getOBD2Values() {
Log.d(TAG, "Before");
writeMessage("Hello");
mNastyBusyWait = true;
while(mNastyBusyWait){ //send Thread to sleep
try {
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Log.d(TAG, "After");
}
The thread should wait until the handler receives the answer :
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
mNastyBusyWait = false; // wake Thread up again
Log.d(TAG, "NOT IN IF :MESSAGE_READ: " + readMessage);
break;
This is a silly busy-wait approach to get the example running. Afaik the problem is that the Thread waits, but the handler is in the same class and it is never used to go on ... what would be a better approach or how can I solve this problem ? I finally get a answer from the bluetooth client !
Thanks.
Upvotes: 0
Views: 84
Reputation: 121810
You can use a CountDownLatch
if this is a "one shot" lock:
// somewhere in init...
private final CountDownLatch latch = new CountDownLatch(1);
// waiting side...
writeMessage("hello");
latch.await();
Log.d(TAG, "After");
// waking side...
readMessage = ...;
latch.countDown();
Log.d(TAG, ...);
If however you want to reuse the lock, you'll have to use a Semaphore
instead.
Yet another solution would be to use an Executor
and .submit()
a new task to it when you have work to be done.
Upvotes: 1