问题描述
我有一台蓝牙手持打印机,我可以使用 Mac 上的 SPP 连接(使用 Coolterm)与之通信.当我尝试在 Android 上做同样的事情(使用平台 7)时,我遇到了多个问题:
打印机似乎不支持/不需要 PIN 验证.从 OSX 连接时,我只是选择了不使用 pin"选项,然后它就配对了.在 Android 中,当我使用
device.createRfcommSocketToServiceRecord()
时,它总是最终要求我提供 PIN/Key(我没有/不需要).我使用反射技巧解决了这个问题:方法 m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});BluetoothSocket 连接 = (BluetoothSocket) m.invoke(device, 1);
我不确定这是否真的有效,但打印机上闪烁的 LED 停止闪烁,这让我相信它确实有效.
一旦有了套接字,我就尝试使用以下方法将字节数据写入流:
byte[] buffer = new byte[3];缓冲区[0] =(字节)0x8A;缓冲区[1] =(字节)0xC1;缓冲区[2] =(字节)0x04;outStream.write(缓冲区);int 响应 = inStream.read();mySocket.close();
在 OSX 上从 Coolterm 发送相同的三字节序列会从打印机打印测试页.但是,这似乎使线程在 Android 上挂起(读取).
这里有什么我遗漏的吗?
这似乎只在我将频道设置为 1 时才有效.所以这意味着我在这里做一些事情.
@Trevor Page 我认为是在正确的道路上.这是我用来连接基本邮票微控制器的谷歌示例.
<上一页>/** 版权所有 (C) 2009 Android 开源项目** 根据 Apache 许可证 2.0 版(许可证")获得许可;* 除非遵守许可,否则您不得使用此文件.* 您可以在以下网址获取许可证的副本** http://www.apache.org/licenses/LICENSE-2.0** 除非适用法律要求或书面同意,否则软件*根据许可分发是在原样"基础上分发的,* 不提供任何明示或暗示的保证或条件.* 请参阅许可证以了解特定语言的管理权限和* 许可证下的限制.*/包 com.your_package;导入 java.io.IOException;导入 java.io.InputStream;导入 java.io.OutputStream;导入 java.util.UUID;导入 android.bluetooth.BluetoothAdapter;导入 android.bluetooth.BluetoothDevice;导入 android.bluetooth.BluetoothServerSocket;导入 android.bluetooth.BluetoothSocket;导入android.content.Context;导入android.os.Bundle;导入android.os.Handler;导入android.os.Message;导入android.util.Log;/*** 这个类完成了设置和管理蓝牙的所有工作*与其他设备的连接.它有一个线程来监听* 传入连接,用于连接设备的线程,以及* 连接时执行数据传输的线程.*/公共类蓝牙服务{//调试私有静态最终字符串 TAG = "BluetoothService_BoeBot";私有静态最终布尔值 D = true;//创建服务器套接字时 SDP 记录的名称private static final String NAME_SECURE = "BluetoothSecure";private static final String NAME_INSECURE = "BluetoothInsecure";//此应用程序的唯一 UUID私有静态最终 UUID MY_UUID_SECURE =UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");私有静态最终 UUID MY_UUID_INSECURE =UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//成员字段私有最终蓝牙适配器 mAdapter;私有最终处理程序 mHandler;私有AcceptThread mSecureAcceptThread;私有AcceptThread mInsecureAcceptThread;私有连接线程 mConnectThread;私有连接线程 mConnectedThread;私有int mState;//表示当前连接状态的常量公共静态最终 int STATE_NONE = 0;//我们什么都不做公共静态最终 int STATE_LISTEN = 1;//现在监听传入的连接公共静态最终 int STATE_CONNECTING = 2;//现在开始一个传出连接公共静态最终 int STATE_CONNECTED = 3;//现在连接到远程设备/*** 构造函数.准备一个新的 BluetoothChat 会话.* @param context UI 活动上下文* @param handler 将消息发送回 UI Activity 的 Handler*/公共蓝牙服务(上下文上下文,处理程序处理程序){mAdapter = BluetoothAdapter.getDefaultAdapter();mState = STATE_NONE;mHandler = 处理程序;}/*** 设置聊天连接的当前状态* @param state 定义当前连接状态的整数*/私有同步无效 setState(int state){如果 (D)Log.d(TAG, "setState() " + mState + " -> " + state);mState = 状态;//将新状态赋予 Handler,以便 UI Activity 可以更新mHandler.obtainMessage(BoeBot.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();}/*** 返回当前连接状态.*/公共同步 int getState(){返回 mState;}/*** 启动聊天服务.具体启动AcceptThread开始一个* 监听(服务器)模式下的会话.活动调用 onResume() */公共同步无效开始(){如果 (D)Log.d(TAG, "开始");//取消任何试图建立连接的线程如果(mConnectThread!= null){mConnectThread.cancel();mConnectThread = null;}//取消当前运行连接的任何线程如果(mConnectedThread != null){mConnectedThread.cancel();mConnectedThread = null;}setState(STATE_LISTEN);//启动线程以侦听 BluetoothServerSocket如果(mSecureAcceptThread == null){mSecureAcceptThread = new AcceptThread(true);mSecureAcceptThread.start();}如果(mInsecureAcceptThread == null){mInsecureAcceptThread = new AcceptThread(false);mInsecureAcceptThread.start();}}/*** 启动 ConnectThread 以启动与远程设备的连接.* @param device 要连接的蓝牙设备* @param secure 套接字安全类型 - Secure (true) , Insecure (false)*/公共同步无效连接(蓝牙设备设备,布尔安全){如果 (D)Log.d(TAG, "连接到:" + 设备);//取消任何试图建立连接的线程如果(mState == STATE_CONNECTING){如果(mConnectThread!= null){mConnectThread.cancel();mConnectThread = null;}}//取消当前运行连接的任何线程如果(mConnectedThread != null){mConnectedThread.cancel();mConnectedThread = null;}尝试{//启动线程以连接给定的设备mConnectThread = new ConnectThread(设备,安全);mConnectThread.start();setState(STATE_CONNECTING);}catch(异常 e){}}/*** 启动 ConnectedThread 以开始管理蓝牙连接* @param socket 建立连接的蓝牙套接字* @param device 已连接的蓝牙设备*/公共同步无效连接(蓝牙套接字套接字,蓝牙设备设备,最终字符串套接字类型){如果 (D)Log.d(TAG, "已连接, 套接字类型:" + socketType);//取消完成连接的线程如果(mConnectThread!= null){mConnectThread.cancel();mConnectThread = null;}//取消当前运行连接的任何线程如果(mConnectedThread != null){mConnectedThread.cancel();mConnectedThread = null;}//取消接受线程,因为我们只想连接一个设备如果(mSecureAcceptThread != null){mSecureAcceptThread.cancel();mSecureAcceptThread = null;}如果(mInsecureAcceptThread != null){mInsecureAcceptThread.cancel();mInsecureAcceptThread = null;}//启动线程来管理连接并执行传输mConnectedThread = new ConnectedThread(socket, socketType);mConnectedThread.start();//将连接设备的名称发送回 UI Activity消息消息 = mHandler.obtainMessage(BoeBot.MESSAGE_DEVICE_NAME);捆绑捆绑 = 新捆绑();bundle.putString(BoeBot.DEVICE_NAME, device.getName());msg.setData(捆绑);mHandler.sendMessage(msg);setState(STATE_CONNECTED);}/*** 停止所有线程*/公共同步无效停止(){如果 (D)Log.d(TAG, "停止");如果(mConnectThread!= null){mConnectThread.cancel();mConnectThread = null;}如果(mConnectedThread != null){mConnectedThread.cancel();mConnectedThread = null;}如果(mSecureAcceptThread != null){mSecureAcceptThread.cancel();mSecureAcceptThread = null;}如果(mInsecureAcceptThread != null){mInsecureAcceptThread.cancel();mInsecureAcceptThread = null;}setState(STATE_NONE);}/*** 以非同步方式写入ConnectedThread* @param out 要写入的字节数* @see ConnectedThread#write(byte[])*/公共无效写入(字节[]输出){//创建临时对象连接线程 r;//同步一个ConnectedThread的副本同步(这个){如果(mState!= STATE_CONNECTED)返回;r = mConnectedThread;}//执行非同步写入r.write(out);}/*** 表示连接尝试失败并通知UI Activity.*/私人无效连接失败(){//向Activity发送失败消息消息消息 = mHandler.obtainMessage(BoeBot.MESSAGE_TOAST);捆绑捆绑 = 新捆绑();bundle.putString(BoeBot.TOAST, "无法连接设备");msg.setData(捆绑);mHandler.sendMessage(msg);//重新启动服务以重新启动监听模式BluetoothService.this.start();}/*** 表示连接丢失并通知UI Activity.*/私人无效连接丢失(){//向Activity发送失败消息消息消息 = mHandler.obtainMessage(BoeBot.MESSAGE_TOAST);捆绑捆绑 = 新捆绑();bundle.putString(BoeBot.TOAST, "设备连接丢失");msg.setData(捆绑);mHandler.sendMessage(msg);//重新启动服务以重新启动监听模式BluetoothService.this.start();}/*** 此线程在侦听传入连接时运行.它的行为* 像服务器端客户端.它一直运行直到接受连接*(或直到取消).*/私有类 AcceptThread 扩展 Thread{//本地服务器套接字私有最终 BluetoothServerSocket mmServerSocket;私有字符串 mSocketType;公共AcceptThread(布尔安全){BluetoothServerSocket tmp = null;mSocketType = 安全?安全":不安全";//创建一个新的监听服务器套接字尝试{如果(安全){tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, MY_UUID_SECURE);} 别的{tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME_INSECURE,MY_UUID_INSECURE);}} 捕捉(IOException e){Log.e(TAG, "套接字类型:" + mSocketType + "listen() 失败", e);}mmServerSocket = tmp;}@覆盖公共无效运行(){如果 (D){Log.d(TAG, "套接字类型:" + mSocketType + "BEGIN mAcceptThread" + this);}setName("AcceptThread" + mSocketType);BluetoothSocket 套接字 = null;//如果我们没有连接,则监听服务器套接字而(mState!= STATE_CONNECTED){尝试{//这是一个阻塞调用,只会返回一个//连接成功或异常套接字 = mmServerSocket.accept();} 捕捉(IOException e){Log.e(TAG, "套接字类型:" + mSocketType + "accept() 失败", e);休息;}//如果连接被接受如果(套接字!= null){同步(BluetoothService.this){开关(mState){案例STATE_LISTEN:案例状态连接://情况正常.启动连接的线程.已连接(套接字,socket.getRemoteDevice(),mSocketType);休息;案例状态_无:案例STATE_CONNECTED://未准备好或已连接.终止新套接字.尝试{socket.close();} 捕捉(IOException e){Log.e(TAG, "无法关闭不需要的套接字", e);}休息;}}}}如果 (D){Log.i(TAG, "END mAcceptThread, socket Type: " + mSocketType);}}公共无效取消(){如果 (D){Log.d(TAG, "Socket Type" + mSocketType + "cancel" + this);}尝试{mmServerSocket.close();} 捕捉(IOException e){Log.e(TAG, "Socket Type" + mSocketType + "close() of server failed", e);}}}/*** 该线程在尝试建立传出连接时运行* 带设备.它直接穿过;连接要么* 成功或失败.*/私有类 ConnectThread 扩展 Thread{私有最终蓝牙套接字 mmSocket;私有最终蓝牙设备 mmDevice;私有字符串 mSocketType;公共 ConnectThread(蓝牙设备设备,布尔安全){mmDevice = 设备;蓝牙套接字 tmp = null;mSocketType = 安全?安全":不安全";//获取一个 BluetoothSocket 用于与//给定蓝牙设备尝试{如果(安全){tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);} 别的{tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);}} 捕捉(IOException e){Log.e(TAG, "套接字类型:" + mSocketType + "create() failed", e);}mmSocket = tmp;}@覆盖公共无效运行(){Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);setName("ConnectThread" + mSocketType);//始终取消发现,因为它会减慢连接速度mAdapter.cancelDiscovery();//与蓝牙套接字建立连接尝试{//这是一个阻塞调用,只会返回一个//连接成功或异常mmSocket.connect();} 捕捉(IOException e){//关闭套接字尝试{mmSocket.close();} 捕捉(IOException e2){Log.e(TAG, "unable to close() " + mSocketType + " socket during connection failure", e2);}连接失败();返回;}//重置 ConnectThread 因为我们已经完成了同步(BluetoothService.this){mConnectThread = null;}尝试{//启动连接的线程已连接(mmSocket,mmDevice,mSocketType);}catch(异常 e){Log.e(TAG, "", e);}}公共无效取消(){尝试{mmSocket.close();} 捕捉(IOException e){Log.e(TAG, "close() of connect " + mSocketType + "socket failed", e);}}}/*** 此线程在与远程设备连接期间运行.*它处理所有传入和传出的传输.*/私有类 ConnectedThread 扩展 Thread{私有最终蓝牙套接字 mmSocket;私有最终 InputStream mmInStream;私有最终输出流 mmOutStream;公共连接线程(蓝牙套接字套接字,字符串套接字类型){Log.d(TAG, "创建 ConnectedThread:" + socketType);mmSocket = 插座;输入流 tmpIn = null;输出流 tmpOut = null;//获取 BluetoothSocket 输入和输出流尝试{tmpIn = socket.getInputStream();tmpOut = socket.getOutputStream();} 捕捉(IOException e){Log.e(TAG, "临时套接字未创建", e);}mmInStream = tmpIn;mmOutStream = tmpOut;}@覆盖公共无效运行(){Log.i(TAG, "开始 mConnectedThread");字节[]缓冲区=新字节[1024];整数字节;//连接时继续监听 InputStream而(真){尝试{//从 InputStream 中读取字节= mmInStream.read(缓冲区);//将获取的字节发送到 UI ActivitymHandler.obtainMessage(BoeBot.MESSAGE_READ, bytes, -1, buffer).sendToTarget();} 捕捉(IOException e){Log.e(TAG, "断开连接", e);连接丢失();休息;}}}/*** 写入连接的 OutStream.* @param buffer 要写入的字节数*/公共无效写入(字节[]缓冲区){尝试{mmOutStream.write(缓冲区);//将发送的消息分享回 UI ActivitymHandler.obtainMessage(BoeBot.MESSAGE_WRITE, -1, -1, 缓冲区).sendToTarget();} 捕捉(IOException e){Log.e(TAG, "写入异常", e);}}公共无效取消(){尝试{mmSocket.close();} 捕捉(IOException e){Log.e(TAG, "close() of connect socket failed", e);}}}}测试它是否有效.
BluetoothService mService = new BluetoothService(this, mHandler);mService.write(字节);
I have a bluetooth Handheld printer that I am able to communicate to using a SPP connection from my Mac(using Coolterm). When I'm trying to do the same from Android (using platform 7) I am running into multiple issues:
The printer doesn't seem to support/need PIN Authentication. When connecting from OSX, I just selected the option that said "Do not use a pin" and it got paired. In Android, when I use
device.createRfcommSocketToServiceRecord()
, it always ends up asking me for a PIN/Key(which I don't have/need). I solved this using the reflection trick:Method m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class}); BluetoothSocket connection = (BluetoothSocket) m.invoke(device, 1);
I am unsure whether this actually worked, but the blinking LED on the printer stops blinking, which makes me believe it did.
Once I have the socket, I try to write byte data to the stream using:
byte[] buffer = new byte[3]; buffer[0] = (byte) 0x8A; buffer[1] = (byte) 0xC1; buffer[2] = (byte) 0x04; outStream.write(buffer); int response = inStream.read(); mySocket.close();
Sending the same three-byte sequence from Coolterm on OSX printed a test page from the printer. However, this seems to make the thread hang on Android(the read).
Is there something I am missing out here?
EDIT: This seems to work only when I set channel to 1. So that means I am on to something here.
@Trevor Page I think was on the right path. Here is a google's example I've used to connect to a basic stamp micro-controller.
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.your_package; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.UUID; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothServerSocket; import android.bluetooth.BluetoothSocket; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; /** * This class does all the work for setting up and managing Bluetooth * connections with other devices. It has a thread that listens for * incoming connections, a thread for connecting with a device, and a * thread for performing data transmissions when connected. */ public class BluetoothService { // Debugging private static final String TAG = "BluetoothService_BoeBot"; private static final boolean D = true; // Name for the SDP record when creating server socket private static final String NAME_SECURE = "BluetoothSecure"; private static final String NAME_INSECURE = "BluetoothInsecure"; // Unique UUID for this application private static final UUID MY_UUID_SECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private static final UUID MY_UUID_INSECURE = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // Member fields private final BluetoothAdapter mAdapter; private final Handler mHandler; private AcceptThread mSecureAcceptThread; private AcceptThread mInsecureAcceptThread; private ConnectThread mConnectThread; private ConnectedThread mConnectedThread; private int mState; // Constants that indicate the current connection state public static final int STATE_NONE = 0; // we're doing nothing public static final int STATE_LISTEN = 1; // now listening for incoming connections public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection public static final int STATE_CONNECTED = 3; // now connected to a remote device /** * Constructor. Prepares a new BluetoothChat session. * @param context The UI Activity Context * @param handler A Handler to send messages back to the UI Activity */ public BluetoothService(Context context, Handler handler) { mAdapter = BluetoothAdapter.getDefaultAdapter(); mState = STATE_NONE; mHandler = handler; } /** * Set the current state of the chat connection * @param state An integer defining the current connection state */ private synchronized void setState(int state) { if (D) Log.d(TAG, "setState() " + mState + " -> " + state); mState = state; // Give the new state to the Handler so the UI Activity can update mHandler.obtainMessage(BoeBot.MESSAGE_STATE_CHANGE, state, -1).sendToTarget(); } /** * Return the current connection state. */ public synchronized int getState() { return mState; } /** * Start the chat service. Specifically start AcceptThread to begin a * session in listening (server) mode. Called by the Activity onResume() */ public synchronized void start() { if (D) Log.d(TAG, "start"); // Cancel any thread attempting to make a connection if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } // Cancel any thread currently running a connection if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } setState(STATE_LISTEN); // Start the thread to listen on a BluetoothServerSocket if (mSecureAcceptThread == null) { mSecureAcceptThread = new AcceptThread(true); mSecureAcceptThread.start(); } if (mInsecureAcceptThread == null) { mInsecureAcceptThread = new AcceptThread(false); mInsecureAcceptThread.start(); } } /** * Start the ConnectThread to initiate a connection to a remote device. * @param device The BluetoothDevice to connect * @param secure Socket Security type - Secure (true) , Insecure (false) */ public synchronized void connect(BluetoothDevice device, boolean secure) { if (D) Log.d(TAG, "connect to: " + device); // Cancel any thread attempting to make a connection if (mState == STATE_CONNECTING) { if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } } // Cancel any thread currently running a connection if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } try { // Start the thread to connect with the given device mConnectThread = new ConnectThread(device, secure); mConnectThread.start(); setState(STATE_CONNECTING); }catch(Exception e) { } } /** * Start the ConnectedThread to begin managing a Bluetooth connection * @param socket The BluetoothSocket on which the connection was made * @param device The BluetoothDevice that has been connected */ public synchronized void connected(BluetoothSocket socket, BluetoothDevice device, final String socketType) { if (D) Log.d(TAG, "connected, Socket Type:" + socketType); // Cancel the thread that completed the connection if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } // Cancel any thread currently running a connection if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } // Cancel the accept thread because we only want to connect to one device if (mSecureAcceptThread != null) { mSecureAcceptThread.cancel(); mSecureAcceptThread = null; } if (mInsecureAcceptThread != null) { mInsecureAcceptThread.cancel(); mInsecureAcceptThread = null; } // Start the thread to manage the connection and perform transmissions mConnectedThread = new ConnectedThread(socket, socketType); mConnectedThread.start(); // Send the name of the connected device back to the UI Activity Message msg = mHandler.obtainMessage(BoeBot.MESSAGE_DEVICE_NAME); Bundle bundle = new Bundle(); bundle.putString(BoeBot.DEVICE_NAME, device.getName()); msg.setData(bundle); mHandler.sendMessage(msg); setState(STATE_CONNECTED); } /** * Stop all threads */ public synchronized void stop() { if (D) Log.d(TAG, "stop"); if (mConnectThread != null) { mConnectThread.cancel(); mConnectThread = null; } if (mConnectedThread != null) { mConnectedThread.cancel(); mConnectedThread = null; } if (mSecureAcceptThread != null) { mSecureAcceptThread.cancel(); mSecureAcceptThread = null; } if (mInsecureAcceptThread != null) { mInsecureAcceptThread.cancel(); mInsecureAcceptThread = null; } setState(STATE_NONE); } /** * Write to the ConnectedThread in an unsynchronized manner * @param out The bytes to write * @see ConnectedThread#write(byte[]) */ public void write(byte[] out) { // Create temporary object ConnectedThread r; // Synchronize a copy of the ConnectedThread synchronized (this) { if (mState != STATE_CONNECTED) return; r = mConnectedThread; } // Perform the write unsynchronized r.write(out); } /** * Indicate that the connection attempt failed and notify the UI Activity. */ private void connectionFailed() { // Send a failure message back to the Activity Message msg = mHandler.obtainMessage(BoeBot.MESSAGE_TOAST); Bundle bundle = new Bundle(); bundle.putString(BoeBot.TOAST, "Unable to connect device"); msg.setData(bundle); mHandler.sendMessage(msg); // Start the service over to restart listening mode BluetoothService.this.start(); } /** * Indicate that the connection was lost and notify the UI Activity. */ private void connectionLost() { // Send a failure message back to the Activity Message msg = mHandler.obtainMessage(BoeBot.MESSAGE_TOAST); Bundle bundle = new Bundle(); bundle.putString(BoeBot.TOAST, "Device connection was lost"); msg.setData(bundle); mHandler.sendMessage(msg); // Start the service over to restart listening mode BluetoothService.this.start(); } /** * This thread runs while listening for incoming connections. It behaves * like a server-side client. It runs until a connection is accepted * (or until cancelled). */ private class AcceptThread extends Thread { // The local server socket private final BluetoothServerSocket mmServerSocket; private String mSocketType; public AcceptThread(boolean secure) { BluetoothServerSocket tmp = null; mSocketType = secure ? "Secure" : "Insecure"; // Create a new listening server socket try { if (secure) { tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, MY_UUID_SECURE); } else { tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord( NAME_INSECURE, MY_UUID_INSECURE); } } catch (IOException e) { Log.e(TAG, "Socket Type: " + mSocketType + "listen() failed", e); } mmServerSocket = tmp; } @Override public void run() { if (D) { Log.d(TAG, "Socket Type: " + mSocketType + "BEGIN mAcceptThread" + this); } setName("AcceptThread" + mSocketType); BluetoothSocket socket = null; // Listen to the server socket if we're not connected while (mState != STATE_CONNECTED) { try { // This is a blocking call and will only return on a // successful connection or an exception socket = mmServerSocket.accept(); } catch (IOException e) { Log.e(TAG, "Socket Type: " + mSocketType + "accept() failed", e); break; } // If a connection was accepted if (socket != null) { synchronized (BluetoothService.this) { switch (mState) { case STATE_LISTEN: case STATE_CONNECTING: // Situation normal. Start the connected thread. connected(socket, socket.getRemoteDevice(), mSocketType); break; case STATE_NONE: case STATE_CONNECTED: // Either not ready or already connected. Terminate new socket. try { socket.close(); } catch (IOException e) { Log.e(TAG, "Could not close unwanted socket", e); } break; } } } } if (D) { Log.i(TAG, "END mAcceptThread, socket Type: " + mSocketType); } } public void cancel() { if (D) { Log.d(TAG, "Socket Type" + mSocketType + "cancel " + this); } try { mmServerSocket.close(); } catch (IOException e) { Log.e(TAG, "Socket Type" + mSocketType + "close() of server failed", e); } } } /** * This thread runs while attempting to make an outgoing connection * with a device. It runs straight through; the connection either * succeeds or fails. */ private class ConnectThread extends Thread { private final BluetoothSocket mmSocket; private final BluetoothDevice mmDevice; private String mSocketType; public ConnectThread(BluetoothDevice device, boolean secure) { mmDevice = device; BluetoothSocket tmp = null; mSocketType = secure ? "Secure" : "Insecure"; // Get a BluetoothSocket for a connection with the // given BluetoothDevice try { if (secure) { tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE); } else { tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE); } } catch (IOException e) { Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e); } mmSocket = tmp; } @Override public void run() { Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType); setName("ConnectThread" + mSocketType); // Always cancel discovery because it will slow down a connection mAdapter.cancelDiscovery(); // Make a connection to the BluetoothSocket try { // This is a blocking call and will only return on a // successful connection or an exception mmSocket.connect(); } catch (IOException e) { // Close the socket try { mmSocket.close(); } catch (IOException e2) { Log.e(TAG, "unable to close() " + mSocketType + " socket during connection failure", e2); } connectionFailed(); return; } // Reset the ConnectThread because we're done synchronized (BluetoothService.this) { mConnectThread = null; } try { // Start the connected thread connected(mmSocket, mmDevice, mSocketType); }catch(Exception e) { Log.e(TAG, "", e); } } public void cancel() { try { mmSocket.close(); } catch (IOException e) { Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e); } } } /** * This thread runs during a connection with a remote device. * It handles all incoming and outgoing transmissions. */ private class ConnectedThread extends Thread { private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; public ConnectedThread(BluetoothSocket socket, String socketType) { Log.d(TAG, "create ConnectedThread: " + socketType); mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; // Get the BluetoothSocket input and output streams try { tmpIn = socket.getInputStream(); tmpOut = socket.getOutputStream(); } catch (IOException e) { Log.e(TAG, "temp sockets not created", e); } mmInStream = tmpIn; mmOutStream = tmpOut; } @Override public void run() { Log.i(TAG, "BEGIN mConnectedThread"); byte[] buffer = new byte[1024]; int bytes; // Keep listening to the InputStream while connected while (true) { try { // Read from the InputStream bytes = mmInStream.read(buffer); // Send the obtained bytes to the UI Activity mHandler.obtainMessage(BoeBot.MESSAGE_READ, bytes, -1, buffer).sendToTarget(); } catch (IOException e) { Log.e(TAG, "disconnected", e); connectionLost(); break; } } } /** * Write to the connected OutStream. * @param buffer The bytes to write */ public void write(byte[] buffer) { try { mmOutStream.write(buffer); // Share the sent message back to the UI Activity mHandler.obtainMessage(BoeBot.MESSAGE_WRITE, -1, -1, buffer).sendToTarget(); } catch (IOException e) { Log.e(TAG, "Exception during write", e); } } public void cancel() { try { mmSocket.close(); } catch (IOException e) { Log.e(TAG, "close() of connect socket failed", e); } } } }
Test to see if it works.
BluetoothService mService = new BluetoothService(this, mHandler);
mService.write(Bytes);
这篇关于使用带有 android 的手持式蓝牙打印机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!