最重要三个类:
BluetoothAdapter bluetoothAdapter
BluetoothSocket btSocket;
BluetoothDevice device
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.startDiscovery();//开始搜索附近的蓝牙设备,搜索的时候会发出三个广播如下
startDiscovery()方法是一个异步方法,它会对其他蓝牙设备进行搜索,持续时间为12秒。搜索过程其实是在System Service中进行,我们可以通过cancelDiscovery()方法来停止这个搜索。在系统搜索蓝牙设备的过程中,系统可能会发送以下三个广播:ACTION_DISCOVERY_START(开始搜索),ACTION_DISCOVERY_FINISHED(搜索结束)和ACTION_FOUND(找到设备)。ACTION_FOUND这个才是我们想要的。所以在startDiscovery之前我们应该注册一个广播如下:
IntentFilter intentfilter = new IntentFilter(
BluetoothDevice.ACTION_FOUND);
bluetoothReceiver = new BluetoothReceiver();
// 注册bluetoothReceiver
registerReceiver(bluetoothReceiver, intentfilter);
广播接收类BluetoothReceiver的实现如下:
public class BluetoothReceiver extends BroadcastReceiver {
@SuppressLint("ShowToast")
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Toast.makeText(MainActivity.this, "扫描中...", 100).show();
// device对象代表被扫描到的远程设备的对象
// 将搜索到的蓝牙设备在ListView中显示出来
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String str = device.getName() + "|" + device.getAddress();
if (lstDevices.indexOf(str) == -1)// 防止重复添加
lstDevices.add(str); // 获取设备名称和mac地址
adtDevices.notifyDataSetChanged();
}
}
}
private List<String> lstDevices = new ArrayList<String>();
搜索到了之后就会把每一个蓝牙设备的name显示在一个listview中,点击listview中的某个设备之后,就会与之开始连接:
String str = lstDevices.get(arg2);
String[] values = str.split("\\|");
String address = values[1];
Log.e("address", values[1]);
uuid = UUID.fromString(SPP_UUID);
Log.e("uuid", uuid.toString());
// btDev是远端的蓝牙设备,get到之后,用btsocket得到其中的socket,建立连接的套接字
BluetoothDevice btDev = bluetoothAdapter.getRemoteDevice(address);
try {
btSocket = (BluetoothSocket) btDev
.getClass()
.getMethod("createRfcommSocket",
new Class[] { int.class })
.invoke(btDev, Integer.valueOf(1));
} 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();
}
// 取消查找
bluetoothAdapter.cancelDiscovery();
try {
Toast.makeText(MainActivity.this, "正在连接...", Toast.LENGTH_SHORT)
.show();
btSocket.connect();
Log.e(TAG,
" BT connection established, data transfer link open.");
Toast.makeText(MainActivity.this, "连接成功,进入控制界面",
Toast.LENGTH_SHORT).show();
// 打开控制界面
Intent intent = new Intent(MainActivity.this,
CtrlActivity.class);
startActivity(intent);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e(TAG, " Connection failed.", e);
Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT)
.show();
}
btSocket = btDev.createRfcommSocketToServiceRecord(SPP_UUID);
之前用这种方式给btSocket赋值时,btSocket.connect()就是抛出异常,后来改用如下方式就可以正常连接了
btSocket = (BluetoothSocket) btDev
.getClass()
.getMethod("createRfcommSocket",
new Class[] { int.class })
.invoke(btDev, Integer.valueOf(1));
注意在执行connect()操作之前一定要先
bluetoothAdapter.cancelDiscovery();