Android连接蓝牙设备一般有这几个步奏
1、注册蓝牙相关的广播
IntentFilter intent = new IntentFilter();
intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果
intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(searchDevices, intent);
2、搜索蓝牙设备
BluetoothAdapter.getDefaultAdapter().startDiscovery();
3、配对
btDev.createBond();
4、建立连接
private void connect(BluetoothDevice btDev) {
UUID uuid = UUID.fromString(SPP_UUID);
try {
// btSocket = btDev.createRfcommSocketToServiceRecord(uuid);
btSocket =(BluetoothSocket) btDev.getClass().getMethod("createRfcommSocket", new Class[] {
int.class}).invoke(btDev,1);
Log.d("BlueToothTestActivity", "开始连接...");
btSocket.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("BlueToothTestActivity", "开始连接......链接失败");
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
此处不抛出异常即可连接成功
完整代码:
package com.example.bluetoothtest;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content