2013-08-20 97 views
0

我正在研究使用BluetoothChat示例应用程序的应用程序。 在我的主要活动中,我使用了一个在其中加载外部页面的webview。我正在通过与外部页面一起加载的JavaScript处理蓝牙功能。基本上我通过添加下面一行Javascript和本地代码之间的桥梁:如何使用android蓝牙聊天示例应用程序实现池?

myWebView.addJavascriptInterface(new WebAppInterface(this,myWebView), "Android");//I pass a refference to the context and a refference to the webview. 

WebAppInterface是具有所有的公共方法,我可以从Javascript调用类。在这个类中我有如下方法:enableBluetooth,disableBluetooth,listBoundedDevices,连接等。

我正在使用来自BluetoothChat示例应用程序的BluetoothSerialService类。我的设备必须连接到一个嵌入式设备,它接收命令并根据我给出的输入做出不同的回答。一个例子是这样的:当我按在网页视图我叫下面的本机代码的按钮:

while(true){ 
    out.write(requestKey);//send command - where "out" is the OutputStream 
    key = in.read();//get response - where "in" is the InputStream 
    if(key==KEY1){ 
     out.write(activateRFID);//send command - activateRFID 
     rfidTag = in.read();//get response - RFID Tag 
     updateUI(rfidTag);//perform function - update the UI with the tag 
    } 
    else if(key==KEY2){ 
     out.write(deactivateRFID);//send command - deactivate RFID 
     response = in.read();//get response 
    } 
    else if(key==KEY3){ 
     out.write(anotherCommand);//send command - 
     response = in.read();//get response 
    } 
} 

我所试图实现的是将命令发送到另一台设备(请求按键)和执行功能。这必须始终发生(将按键的设备集中在一起并执行特定功能)。

我该如何启动1个单线程来存储设备(写入OutputStream并从InputStream读取响应)? BluetoothChat示例应用程序的工作原理有点不同:每当我调用BluetoothChatSevice.write()时,我都会通过ConnectedThread运行方法获得响应,该方法通过mHandler向UI发送消息。

欢迎您提出任何建议。

回答

0

我今天做到了。我建议你做一个布尔函数readWrite(),每当你写outputStream的时候,你也可以从inputStream中读取数据,并使用mHandler将readBuffer发送给UI。如果读写都正常,则返回true,如果其中一个出错而不是返回false,并在关闭ConnectedThread之前使用resetConection。请参阅我的答案以获取resetConnection。 Application using bluetooth SPP profile not working after update from Android 4.2 to Android 4.3

但是关于池的回答是: 在ConnectedThread run()方法做了一段时间(真),呼叫类似读写方法(字节[]数据)的环内,其中摆在首位你写了一些东西给设备,然后你从输入流(从设备)读取数据。在这个readWrite()方法中,如果写入outpustream很好,那么继续从输入流中读取。如果您有任何数据到输入流,请将数据发送到UI以使用mHandler进行处理(或者在发送到UI之前执行一些处理)。

它对我来说非常好。