The problem here is that waitarrival()
is blocking your ui thread, specifically the call to read()
.
What you'd want to do instead is:
public int waitarrival() {
while( Global.mmInStream.available() > 1 ) { // at least one byte available
byte data = Global.mmInStream.read(); // read just one byte, that's all we need
if( data == 30 ) {
return 1; // if we received the '30' we were looking for, then we're good to go.
}
}
return 0; // this is returned in all other cases -- i.e. no byte available, or no 30s.
}
Once that's done, you'd probably want check this periodically to see if there was a reaction from the bluetooth device. You could look at the Android Bluetooth Chat sample to see how to properly put the entire thing on a background thread -- that's the preferred pattern for this.
If you're really want to wait for this, and handle your own timeout, you could wrap this entire method into an AsyncTask
, with something like this --
protected Integer doInBackGround( Integer[] timeout ) {
long targetTime = System.CurrentTimeMillis() + timeout[0] * 1000; // time out in seconds...
while( System.CurrentTimeMillis() < targetTime ) {
if( waitforarrival() == 1 )
return 1;
Thread.sleep(100); // sleep 1/10th of a second
}
return 0;
}
Your onPostExecute()
would then update the UI based on the result.
And then you'd invoke it from onCreate()
like so:
myTask.execute( 60 ); // wait for arrival for a minute.