Android蓝牙通讯(服务端、客户端)
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                Android蓝牙通讯(服务端、客户端)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                Android藍牙通訊
1. 在AndroidManifest.xml文件添加藍牙操作權限
<uses-permission android:name="android.permission.BLUETOOTH" /><uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />2. 收發數據處理類
public class MyDataProcessThread extends Thread {private BluetoothSocket socket;private InputStream inputStream;private OutputStream outputStream;private static final int MAX_SIZE = 1024;private boolean isRunning = true;public MyDataProcessThread(BluetoothSocket socket) {this.socket = socket;try {inputStream = socket.getInputStream();outputStream = socket.getOutputStream();} catch (IOException e) {e.printStackTrace();}}@Overridepublic void run() {byte[] buffer = new byte[MAX_SIZE];int readByte;while (isRunning) {try {readByte = inputStream.read(buffer);if (readByte != -1) {byte[] out = new byte[readByte];System.arraycopy(buffer, 0, out, 0, readByte);//接收到的數據byte[] reData = DataPackage.packB3(out);write(reData);}} catch (Exception e) {e.printStackTrace();break;}}}/*** 發送數據到遠程藍牙* @param data 準備發送的數據* @return 發送是否成功* */public boolean write(byte[] data) {try {outputStream.write(data);return true;} catch (IOException e) {e.printStackTrace();return false;}}/*** 關閉數據收發相關流對象* */public void cancel() {try {isRunning = false;this.interrupt();if (outputStream != null) {outputStream.close();outputStream = null;}if (inputStream != null) {inputStream.close();inputStream = null;}if (socket != null) {socket.close();socket = null;}} catch (IOException e) {e.printStackTrace();}} }3. 服務端
public class MyBluetoothServer extends Thread {private BluetoothServerSocket serverSocket;private static final UUID UUID_ANDROID_DEVICE =UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");private static final UUID UUID_OTHER_DEVICE =UUID.fromString("00001105-0000-1000-8000-00805F9B34FB");private static final String NAME_SECURE = "BluetoothChatSecure";private static final String NAME_INSECURE = "BluetoothChatInsecure";private boolean isSecure = true;private boolean isAndroidDevice = false;private List<MyDataProcessThread> threads;private boolean isRunning = true;public MyBluetoothServer() {Log.w(this.getClass().getName(), "create");BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();BluetoothServerSocket temp = null;try {if (isAndroidDevice) {if (isSecure) {temp = adapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, UUID_ANDROID_DEVICE);} else {temp = adapter.listenUsingRfcommWithServiceRecord(NAME_INSECURE, UUID_ANDROID_DEVICE);}} else {if (isSecure) {temp = adapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, UUID_OTHER_DEVICE);} else {temp = adapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, UUID_OTHER_DEVICE);}}} catch (IOException e) {e.printStackTrace();}serverSocket = temp;threads = new ArrayList<>();}@Overridepublic void run() {Log.w(getName(), "run");isRunning = true;while (isRunning) {try {BluetoothSocket socket = serverSocket.accept();Log.w(this.getClass().getName(), "accept");if (socket != null) {MyDataProcessThread thread = new MyDataProcessThread(socket);thread.start();threads.add(thread);Log.w(this.getClass().getName(), "threads size = " + threads.size());}} catch (Exception e) {e.printStackTrace();break;}}}public void cancel() {isRunning = false;this.interrupt();for (MyDataProcessThread thread : threads) {thread.cancel();}threads.clear();if (serverSocket != null) {try {serverSocket.close();} catch (IOException e) {e.printStackTrace();}}} }4.客戶端
public class MyBluetoothClient extends Thread {private BluetoothSocket socket;private static final UUID UUID_ANDROID_DEVICE =UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");private static final UUID UUID_OTHER_DEVICE =UUID.fromString("00001105-0000-1000-8000-00805F9B34FB");private final static int TIME_OUT = 10000;private boolean isSecure = true;private boolean isAndroidDevice = false;private MyDataProcessThread thread;public MyBluetoothClient(BluetoothDevice device) {BluetoothSocket temp = null;try {if (isSecure) {if (isAndroidDevice) {temp = device.createRfcommSocketToServiceRecord(UUID_ANDROID_DEVICE);} else {temp = device.createRfcommSocketToServiceRecord(UUID_OTHER_DEVICE);}} else {if (isAndroidDevice) {temp = device.createInsecureRfcommSocketToServiceRecord(UUID_ANDROID_DEVICE);} else {temp = device.createInsecureRfcommSocketToServiceRecord(UUID_OTHER_DEVICE);}}} catch (Exception e) {e.printStackTrace();}socket = temp;}@Overridepublic void run() {if (socket == null) {return;}try {socket.connect();} catch (IOException e) {e.printStackTrace();cancel();}thread = new MyDataProcessThread(socket);thread.start();}/*** 發送數據* @param data 字節數據* @return 發送結果,true - 發送成功; false - 發送失敗* */public boolean write(byte[] data) {return thread.write(data);}/*** 關閉相關流對象* */public void cancel() {try {if (thread != null) {thread.cancel();}if (socket != null) {socket.close();}} catch (Exception e) {e.printStackTrace();}} }5.Activity相關調用
1). 獲取已配對藍牙設備
private BluetoothDevice device; private void showBondedDevice() {BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();if (adapter == null) {return;}if (!adapter.isEnabled()) {//打開系統藍牙設置Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);startActivity(intent);return;}Set<BluetoothDevice> devices = adapter.getBondedDevices();if (devices.size() > 0) {for (BluetoothDevice item : devices) {Log.i("BondedDevices", "device : " + item.getName());}}}2). 服務端調用
private void startServer() {MyBluetoothServer server = new MyBluetoothServer();server.start();}3). 客戶端調用
private MyBluetoothClient client;/*** 連接某個已配對藍牙設備* */private void startClient() {client = new MyBluetoothClient(device);client.start();}/*** 在子線程中發送數據* @param data 要發送的數據* */private void write(final byte[] data) {new Thread(new Runnable() {@Overridepublic void run() {client.write(data);}}).start();}總結
以上是生活随笔為你收集整理的Android蓝牙通讯(服务端、客户端)的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: vscode 创建Express框架 目
- 下一篇: 疯狂Android讲义(一)——第一部分
