Android 连接到蓝牙设备时出现问题
我正在尝试使用下面的代码连接到设备。。。基本上是从BTchat源代码修改的。一切似乎都进行得很顺利,但设备没有响应命令,我的手机仍然显示已配对但未连接,设备显示未连接。这让我非常确定它确实没有连接,但没有发生错误 我能拿错UUID吗 日志上写着:Android 连接到蓝牙设备时出现问题,android,bluetooth,Android,Bluetooth,我正在尝试使用下面的代码连接到设备。。。基本上是从BTchat源代码修改的。一切似乎都进行得很顺利,但设备没有响应命令,我的手机仍然显示已配对但未连接,设备显示未连接。这让我非常确定它确实没有连接,但没有发生错误 我能拿错UUID吗 日志上写着: 04-30 18:51:10.116: DEBUG/BluetoothService(1228): uuid(application): 00001101-0000-1000-8000-00805f9b34fb 1 04-30 18:51:1
04-30 18:51:10.116: DEBUG/BluetoothService(1228): uuid(application): 00001101-0000-1000-8000-00805f9b34fb 1
04-30 18:51:10.116: DEBUG/BluetoothService(1228): Making callback for 00001101-0000-1000-8000-00805f9b34fb with result 1
04-30 18:51:10.131: VERBOSE/BluetoothEventRedirector(31561): Received android.bleutooth.device.action.UUID
我的代码正在打印到它连接的日志中:
04-30 18:53:21.210: DEBUG/BTComm(1044): connect to: K4500-620963
04-30 18:53:21.225: INFO/BTComm(1044): BEGIN ConnectThread
04-30 18:53:26.272: DEBUG/BTComm(1044): connected to: K4500-620963
04-30 18:53:26.272: DEBUG/BTComm(1044): create ConnectedThread
04-30 18:53:26.280: DEBUG/BTComm(1044): setState() 0 -> 3
04-30 18:53:26.280: INFO/BTComm(1044): BEGIN ConnectedThread
这是我的全部代码:
p
ublic类BTCom{
//调试
私有静态最终字符串TAG=“BTComm”;
私有静态最终布尔值D=true;
专用静态最终UUID UUID=UUID.fromString(“00001101-0000-1000-8000-00805F9B34FB”);
//成员字段
专用最终蓝牙适配器;
私人最终处理人;
私有连接线程连接线程;
私有连接线程连接线程;
私人和国家;
私人语境;
私人蓝牙设备;
//指示当前连接状态的常量
public static final int STATE_NONE=0;//我们什么也没做
public static final int STATE_LISTEN=1;//正在侦听传入连接
public static final int STATE_CONNECTING=2;//正在启动传出连接
public static final int STATE_CONNECTED=3;//现在已连接到远程设备
公共BTCom(上下文、处理程序){
adapter=BluetoothAdapter.getDefaultAdapter();
状态=状态\无;
this.handler=handler;
this.context=上下文;
}
专用无效检查蓝牙(){
//检查设备是否支持蓝牙
if(适配器==null){
Toast.makeText(上下文,“错误:此设备不支持蓝牙通信”
,Toast.LENGTH_LONG)show();
返回;
}
//现在确保蓝牙已启用
如果(!adapter.isEnabled()){
//如果没有,则提示用户
Intent enablebintent=新意图(BluetoothAdapter.ACTION\u REQUEST\u ENABLE);
上下文。启动触觉(enableBtIntent);
}
}
公共蓝牙设备getBTDevice(){
Set pairedDevices=adapter.getBondedDevices();
BluetoothDevice foundDevice=null;
BTDevice=null;
//如果有配对的设备
如果(pairedDevices.size()>0){
//循环通过配对设备
用于(蓝牙设备:pairedDevices){
//检查名称是否符合K4xxx-xxxxxx模式
如果(device.getName().matches(“K4\\d\\d\\d-\\d\\d\\d\\d\\d”){
foundDevice=设备;
打破
}
}
如果(foundDevice==null){//如果我们没有找到任何
Toast.makeText(上下文,
错误:找不到配对的BTDevice设备,请配对BTDevice设备以继续
,Toast.LENGTH_LONG)show();
返回null;
}
}
return foundDevice;//找到一个BTDevice!
}
/**
*设置聊天室连接的当前状态
*@param state定义当前连接状态的整数
*/
私有同步无效设置状态(int状态){
如果(D)Log.D(标记“setState()”+this.state+“->”+state);
this.state=状态;
}
/**
*启动ConnectThread以启动到远程设备的连接。
*@param device要连接的蓝牙设备
*/
公共同步void connect(蓝牙设备){
Log.d(标记“连接到:”+device.getName());
//取消任何试图建立连接的线程
如果(connectThread!=null){connectThread.cancel();connectThread=null;}
//取消当前运行连接的任何线程
如果(connectedThread!=null){connectedThread.cancel();connectedThread=null;}
//启动线程以与给定设备连接
connectThread=新的connectThread(设备);
connectThread.start();
}
/**
*启动ConnectedThread以开始管理蓝牙连接
*@param socket连接的BluetoothSocket
*@param device已连接的蓝牙设备
*/
已连接公共同步无效(蓝牙套接字、蓝牙设备){
Log.d(标记“连接到:”+device.getName());
//取消完成连接的线程
如果(connectThread!=null){connectThread.cancel();connectThread=null;}
//取消当前运行连接的任何线程
如果(connectedThread!=null){connectedThread.cancel();connectedThread=null;}
//启动线程以管理连接并执行传输
connectedThread=新的connectedThread(套接字);
connectedThread.start();
设置状态(连接状态);
}
/**
*停止所有线程
*/
公共同步无效停止(){
如果(D)Log.D(标记“停止”);
if(connectThread!=null){
connectThread.cancel();
connectThread=null;
}
if(connectedThread!=null){
connectedThread.cancel();
connectedThread=null;
设置状态(无状态);
}
}
/**
*以非同步方式写入ConnectedThread
*@param输出要写入的字节
*@请参阅ConnectedThread#write(字节[])
*/
公共无效写入(字节[]输出){
//创建临时对象
连接线程r;
//同步ConnectedThread的副本
已同步(此){
如果(state!=state_CONNECTED)返回;
r=连接的线程;
}
//执行非同步写入
r、 写出;
}
私人C类
ublic class BTCom {
// Debugging
private static final String TAG = "BTComm";
private static final boolean D = true;
private static final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Member fields
private final BluetoothAdapter adapter;
private final Handler handler;
private ConnectThread connectThread;
private ConnectedThread connectedThread;
private int state;
private Context context;
private BluetoothDevice BTDevice;
// 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
public BTCom(Context context, Handler handler) {
adapter = BluetoothAdapter.getDefaultAdapter();
state = STATE_NONE;
this.handler = handler;
this.context = context;
}
private void checkBluetooth(){
// check if device supports bluetooth
if (adapter == null) {
Toast.makeText(context, "ERROR: This device does not support Bluetooth communication"
, Toast.LENGTH_LONG).show();
return;
}
// now make sure bluetooth is enabled
if (!adapter.isEnabled()) {
// if not, then prompt the user
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
context.startActivity(enableBtIntent);
}
}
public BluetoothDevice getBTDevice(){
Set<BluetoothDevice> pairedDevices = adapter.getBondedDevices();
BluetoothDevice foundDevice = null;
BTDevice = null;
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// check if the name fits the pattern K4xxx-xxxxxx
if (device.getName().matches("K4\\d\\d\\d-\\d\\d\\d\\d\\d\\d")){
foundDevice = device;
break;
}
}
if (foundDevice == null){ // if we didn't find any
Toast.makeText(context,
"ERROR: No paired BTDevice device was found, please pair a BTDevice device to continue"
, Toast.LENGTH_LONG).show();
return null;
}
}
return foundDevice; // found a BTDevice!
}
/**
* 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() " + this.state + " -> " + state);
this.state = state;
}
/**
* Start the ConnectThread to initiate a connection to a remote device.
* @param device The BluetoothDevice to connect
*/
public synchronized void connect(BluetoothDevice device) {
Log.d(TAG, "connect to: " + device.getName());
// Cancel any thread attempting to make a connection
if (connectThread != null) {connectThread.cancel(); connectThread = null;}
// Cancel any thread currently running a connection
if (connectedThread != null) {connectedThread.cancel(); connectedThread = null;}
// Start the thread to connect with the given device
connectThread = new ConnectThread(device);
connectThread.start();
}
/**
* 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) {
Log.d(TAG, "connected to: " + device.getName());
// Cancel the thread that completed the connection
if (connectThread != null) {connectThread.cancel(); connectThread = null;}
// Cancel any thread currently running a connection
if (connectedThread != null) {connectedThread.cancel(); connectedThread = null;}
// Start the thread to manage the connection and perform transmissions
connectedThread = new ConnectedThread(socket);
connectedThread.start();
setState(STATE_CONNECTED);
}
/**
* Stop all threads
*/
public synchronized void stop() {
if (D) Log.d(TAG, "stop");
if (connectThread != null) {
connectThread.cancel();
connectThread = null;
}
if (connectedThread != null) {
connectedThread.cancel();
connectedThread = 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 (state != STATE_CONNECTED) return;
r = connectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
private class ConnectThread extends Thread {
private final BluetoothSocket socket;
private final BluetoothDevice device;
public ConnectThread(BluetoothDevice device) {
this.device = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
Log.e(TAG, "Socket create failed", e);
}
socket = tmp;
}
public void run() {
Log.i(TAG, "BEGIN ConnectThread");
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket.connect();
} catch (IOException e) {
// Close the socket
try {
socket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() socket during connection failure", e2);
}
return;
}
// Reset the ConnectThread because we're done
synchronized (BTCom.this) {
connectThread = null;
}
// Start the connected thread
connected(socket, this.device);
}
public void cancel() {
try {
socket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect 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 socket;
private final InputStream inStream;
private final OutputStream outStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "create ConnectedThread");
this.socket = 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);
}
inStream = tmpIn;
outStream = tmpOut;
}
public void run() {
Log.i(TAG, "BEGIN ConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = inStream.read(buffer);
// Send the obtained bytes to the UI Activity
handler.obtainMessage(KestrelTest.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
// Start the service over to restart listening mode
break;
}
}
}
/**
* Write to the connected OutStream.
* @param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
outStream.write(buffer);
Log.i(TAG, "Sending " + buffer.length + " bytes");
Log.i(TAG, "Sending: " + new String(buffer));
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
public void cancel() {
try {
socket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
}