我正在尝试从主线程中的缓冲区(蓝牙InputStream)读取数据。我还创建了一个计时器处理程序。如果数据到达,则立即将其返回;如果数据在30秒内未到达,则退出循环。
public boolean isTimerFired = false;
//isTimerFired is declared globally and initialised first false;
public String readDataBuffer(){
final int intervalTime = 30000; // 30 sec
//Timer Handler to count till 30 sec
Handler timerHandler = new Handler();
timerHandler.postDelayed(new Runnable() {
@Override
public void run() {
isTimerFired=true; // After timer is triggered it is made false.
}
}, intervalTime);
// Main Thread to read InputStream
while(!isTimerFired)
{
inputStream = null;
try {
inputStream = socket.getInputStream();
if (inputStream.available() > 0)
{
byte[] buffer = new byte[1024];
inputStream.read(buffer);
tempMsg = new String(buffer, 0, 1);
Log.d("==>msg", "tempMsg=" + tempMsg);
break;
}
}
catch (Exception e)
{ }
}
isTimerFired=false;
return tempMsg;
}