Pop*_*día 10 android timeout bluetooth inputstream
是否可以在Android中的BluetoothSocket中实现inputstream.read()函数的超时?
我尝试过使用Thread.sleep(),但这只会暂停我的活动.
---更新---
我有一个想法,在这里编写2个线程代码(t1和t2),其中每个线程中断其他,其中一个(t1)进行休眠(5000)然后中断另一个线程(t2),从另一个线程中断另一个线程( t2)如果在读取时输入流检测到某个字符为0x0D中断另一个线程(t1),但这是我的问题,有人可以帮助我吗?因为我没有使用thread()方法的线程,希望有人能帮助我,谢谢...
---更新---
public void run(){
while(true){
try {
char r;
String respuesta = "";
while (true) {
r = (char) mmInStream.read();
respuesta += r;
if (r == 0x3e) {
break;
}
}
respuesta = respuesta.replaceAll(" ", "");
Log.d("respuesta", respuesta);
rHandler.obtainMessage(MESSAGE_READ, -1, -1, respuesta).sendToTarget();
} catch (IOException readException) {
Log.e("ServicioGeneral", "Error de lectura", readException);
this.interrupt();
connectionLost();
// posibly break();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的实现,当某些东西进入不同的线程时,问题是如果我没有从de mmInStream获取0x3e字符,将达到超时.
我想在第二个例子中我必须使用notifyAll(),但是,什么时候我必须启动readThread()?
谢谢,@ weeman
job*_*bnz 10
你可以这样做:
InputStream in = someBluetoothSocket.getInputStream();
int timeout = 0;
int maxTimeout = 8; // leads to a timeout of 2 seconds
int available = 0;
while((available = in.available()) == 0 && timeout < maxTimeout) {
timeout++;
// throws interrupted exception
Thread.sleep(250);
}
byte[] read = new byte[available];
in.read(read);
Run Code Online (Sandbox Code Playgroud)
这样,您最初可以从具有特定超时的流中读取.如果你想在任何阅读时间实现超时,你可以尝试这样的事情:
Thread readThread = new ReadThread(); // being a thread you use to read from an InputStream
try {
synchronized (readThread) {
// edit: start readThread here
readThread.start();
readThread.wait(timeOutInMilliSeconds);
}
catch (InterruptedException e) {}
Run Code Online (Sandbox Code Playgroud)
使用此方法,如果线程实际从输入流中读取内容,您可能需要某种事件处理程序来通知您的应用程序.
我希望有所帮助!
- - 编辑:
我没有使用任何处理程序实现了一个示例.
Socket s = new Socket("localhost", 8080);
final InputStream in = s.getInputStream();
Thread readThread = new Thread(new Runnable() {
public void run() {
int read = 0;
try {
while((read = in.read()) >= 0) {
System.out.println(new String(new byte[]{ (byte) read }));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
synchronized (readThread) {
readThread.start();
try {
readThread.wait(2000);
if(readThread.isAlive()) {
// probably really not good practice!
in.close();
System.out.println("Timeout exceeded!");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15178 次 |
| 最近记录: |