【发布时间】:2015-06-16 00:30:06
【问题描述】:
我正在尝试通过蓝牙打印到热敏打印机。
我之前能够在 Nexus 7 设备(第一代和第二代)上成功打印。但是,当我将完全相同的代码复制粘贴到不同的应用程序并将其部署到华硕平板电脑上时,我突然收到一个IOException,告诉我我的套接字可能已关闭。
这是我的代码:
public void onPrintReceipt(){
Toast.makeText(getApplicationContext(), "Printing", Toast.LENGTH_LONG).show();
try{
Set<BluetoothDevice> bdevices = bluetoothAdapter.getBondedDevices();
blueToothDevice = bluetoothAdapter.getRemoteDevice("00:01:90:EE:B2:52");
simpleComm(1);
}
catch(Exception ex){
Log.e("", "simpleComm() Catch Statement Entered");
}
}
protected void simpleComm(Integer port){
//InputStream tmpIn = null;
byte[] buffer = new byte[3]; //{65,65,53,53,49,52,65,66,67,68};
buffer[0] = (byte) 0x08;
buffer[1] = (byte) 0x99;
buffer[2] = (byte) 0x04;
OutputStream tmpOut;// = null;
bluetoothAdapter.cancelDiscovery();
Log.e(this.toString(), "Port = " + port);
try {
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
Method m = blueToothDevice.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
socket = (BluetoothSocket) m.invoke(blueToothDevice, port);
// assert (socket != null) : "Socket is Null";
if(socket.isConnected()){
socket.close();
}
socket.connect();
try {
Log.e(this.toString(), "************ CONNECTION SUCCEES! *************");
try{
//tmpIn=socket.getInputStream();
tmpOut = socket.getOutputStream();
//mmInStream = tmpIn;
mmOutStream = tmpOut;
out = new BufferedWriter(new OutputStreamWriter(mmOutStream));
}
catch(Exception ex){
Log.e(this.toString(), "Exception " + ex.getMessage());
}
//TODO print sequence starts here
//....snip snip a LOT of code
}
finally{
mmOutStream.flush();
mmOutStream.close();
socket.close();
}
}
catch (IOException ex){
Log.e(this.toString(), "IOException: " + ex.getMessage());
}
catch (NoSuchMethodException ex){
Log.e(this.toString(), "NoSuchMethodException: " + ex.getMessage());
}
catch (IllegalAccessException ex){
Log.e(this.toString(), "IllegalAccessException: " + ex.getMessage());
}
catch (InvocationTargetException ex){
Log.e(this.toString(), "InvocationTargetException: " + ex.getMessage());
}
}
这是来自 try-catch 块的错误:
IOException: read failed, socket might closed or timeout, read ret: -1
现在我很困惑,为什么我所做的只是将代码部署在不同的设备上时突然出现错误。
我该如何继续?
【问题讨论】:
-
“现在我很困惑,为什么我所做的只是在不同的设备上部署代码时突然出现错误。” 因为 BT 的编码很糟糕。不同的设备/型号/版本之间可能会有所不同。但是
connect()会发生什么?似乎有些东西没有正确执行。 -
@codeMagic 似乎就是这样。我刚刚将我在 Acer 平板电脑上尝试运行的完全相同的代码运行到我的 Nexus 7 设备上。 Nexus 7 设备通过蓝牙打印到热敏打印机没有问题。看起来有一些较低级别的交互即将到来。
-
Tell me 关于它....Bt is fun!。但它似乎仍然与您的
connect()方法有关。也许可以更改其中的某些内容以使其正常工作。
标签: java android sockets bluetooth