藍牙功能
打開藍牙
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();
}