蓝牙功能
打开蓝牙
private void open() {
Intent intent = new Intent();
intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(intent, 200);
}
关闭蓝牙
private void close() {
bluetoothAdapter.disable();
}
搜索附近蓝牙
private void search() {
bluetoothDeviceList_left.clear();
Toast.makeText(this, "开始搜索", Toast.LENGTH_SHORT).show();
bluetoothAdapter.startDiscovery();
}
配对蓝牙发送数据
private void show() {
bluetoothDeviceList_right.clear();
Toast.makeText(this, "显示已配对", Toast.LENGTH_SHORT).show();
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
bluetoothDeviceList_right.addAll(bondedDevices);
myBlueAdapter_right.notifyDataSetChanged();
}
其余的部分
private void Servicess() {
Log.i(TAG, "Servicess: ");
Toast.makeText(this, "开启服务", Toast.LENGTH_SHORT).show();
new Thread(new Runnable() {
@Override
public void run() {
try {
BluetoothServerSocket serverSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(bluetoothAdapter.getName(), uuid);
Log.i(TAG, "run: 进入线程");
while (true){
Log.i(TAG, "run: 进入死循环");
BluetoothSocket socket = serverSocket.accept();
Message obtain = Message.obtain();
obtain.what = 101;
obtain.obj = socket.getRemoteDevice().getName();
handler.sendMessage(obtain);
new ServiceThread(socket,handler).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}