找回密碼
 立即注冊

QQ登錄

只需一步,快速開始

搜索
查看: 3771|回復(fù): 1
收起左側(cè)

Android藍牙調(diào)試助手源碼分享

[復(fù)制鏈接]
ID:420684 發(fā)表于 2018-11-4 20:06 | 顯示全部樓層 |閱讀模式
0.png
下載:
藍牙調(diào)試助手.zip (121.49 KB, 下載次數(shù): 50)

部分源碼預(yù)覽:
  1. package com.example.android.BluetoothChat;
  2. /**
  3. * 描述:藍牙服務(wù)核心類
  4. */
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.OutputStream;
  8. import java.util.UUID;

  9. import android.bluetooth.BluetoothAdapter;
  10. import android.bluetooth.BluetoothDevice;
  11. import android.bluetooth.BluetoothServerSocket;
  12. import android.bluetooth.BluetoothSocket;
  13. import android.content.Context;
  14. import android.os.Bundle;
  15. import android.os.Handler;
  16. import android.os.Message;
  17. import android.util.Log;
  18. public class BluetoothChatService {
  19.     // 測試數(shù)據(jù)
  20.     private static final String TAG = "BluetoothChatService";
  21.     private static final boolean D = true;

  22.     private static final String NAME = "BluetoothChat";

  23.     // 聲明一個唯一的UUID
  24.     private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");        //change by chongqing jinou        

  25.     private final BluetoothAdapter mAdapter;
  26.     private final Handler mHandler;
  27.     private AcceptThread mAcceptThread;
  28.     private ConnectThread mConnectThread;
  29.     private ConnectedThread mConnectedThread;
  30.     private int mState;

  31.     // 常量,顯示當(dāng)前的連接狀態(tài)
  32.     public static final int STATE_NONE = 0;
  33.     public static final int STATE_LISTEN = 1;
  34.     public static final int STATE_CONNECTING = 2;
  35.     public static final int STATE_CONNECTED = 3;
  36.    
  37.     public BluetoothChatService(Context context, Handler handler) {
  38.         mAdapter = BluetoothAdapter.getDefaultAdapter();
  39.         mState = STATE_NONE;
  40.         mHandler = handler;
  41.     }

  42.     /**
  43.      * 設(shè)置當(dāng)前的連接狀態(tài)
  44.      * @param state  連接狀態(tài)
  45.      */
  46.     private synchronized void setState(int state) {
  47.         if (D) Log.d(TAG, "setState() " + mState + " -> " + state);
  48.         mState = state;

  49.         // 通知Activity更新UI
  50.         mHandler.obtainMessage(BluetoothChatActivity.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
  51.     }

  52.     /**
  53.      * 返回當(dāng)前連接狀態(tài)
  54.      *
  55.      */
  56.     public synchronized int getState() {
  57.         return mState;
  58.     }

  59.     /**
  60.      *開始聊天服務(wù)
  61.      *
  62.      */
  63.     public synchronized void start() {
  64.         if (D) Log.d(TAG, "start");

  65.         if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}

  66.         if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

  67.         if (mAcceptThread == null) {
  68.             mAcceptThread = new AcceptThread();
  69.             mAcceptThread.start();
  70.         }
  71.         setState(STATE_LISTEN);
  72.     }

  73.     /**
  74.      * 連接遠程設(shè)備
  75.      * @param device  連接
  76.      */
  77.     public synchronized void connect(BluetoothDevice device) {
  78.         if (D) Log.d(TAG, "連接到: " + device);

  79.         if (mState == STATE_CONNECTING) {
  80.             if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
  81.         }

  82.         if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

  83.         mConnectThread = new ConnectThread(device);
  84.         mConnectThread.start();
  85.         setState(STATE_CONNECTING);
  86.     }

  87.     /**
  88.      * 啟動ConnectedThread開始管理一個藍牙連接
  89.      */
  90.     public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
  91.         if (D) Log.d(TAG, "連接");

  92.         if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}

  93.         if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

  94.         if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}

  95.         mConnectedThread = new ConnectedThread(socket);
  96.         mConnectedThread.start();

  97.         Message msg = mHandler.obtainMessage(BluetoothChatActivity.MESSAGE_DEVICE_NAME);
  98.         Bundle bundle = new Bundle();
  99.         bundle.putString(BluetoothChatActivity.DEVICE_NAME, device.getName());
  100.         msg.setData(bundle);
  101.         mHandler.sendMessage(msg);

  102.         setState(STATE_CONNECTED);
  103.     }

  104.     /**
  105.      * 停止所有線程
  106.      */
  107.     public synchronized void stop() {
  108.         if (D) Log.d(TAG, "stop");
  109.         setState(STATE_NONE);
  110.         if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
  111.         if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
  112.         if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}
  113.     }

  114.     /**
  115.      * 以非同步方式寫入ConnectedThread
  116.      * @param out
  117.      */
  118.     public void write(byte[] out) {
  119.         ConnectedThread r;
  120.         synchronized (this) {
  121.             if (mState != STATE_CONNECTED) return;
  122.             r = mConnectedThread;
  123.         }
  124.         r.write(out);
  125.     }

  126.     /**
  127.      * 無法連接,通知Activity
  128.      */
  129.     private void connectionFailed() {
  130.         setState(STATE_LISTEN);
  131.         
  132.         Message msg = mHandler.obtainMessage(BluetoothChatActivity.MESSAGE_TOAST);
  133.         Bundle bundle = new Bundle();
  134.         bundle.putString(BluetoothChatActivity.TOAST, "無法連接設(shè)備");
  135.         msg.setData(bundle);
  136.         mHandler.sendMessage(msg);
  137.     }

  138.     /**
  139.      * 設(shè)備斷開連接,通知Activity
  140.      */
  141.     private void connectionLost() {

  142.         Message msg = mHandler.obtainMessage(BluetoothChatActivity.MESSAGE_TOAST);
  143.         Bundle bundle = new Bundle();
  144.         bundle.putString(BluetoothChatActivity.TOAST, "設(shè)備斷開連接");
  145.         msg.setData(bundle);
  146.         mHandler.sendMessage(msg);
  147.     }

  148.     /**
  149.      * 監(jiān)聽傳入的連接
  150.      */
  151.     private class AcceptThread extends Thread {
  152.         private final BluetoothServerSocket mmServerSocket;

  153.         public AcceptThread() {
  154.             BluetoothServerSocket tmp = null;

  155.             try {
  156.                 tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
  157.             } catch (IOException e) {
  158.                 Log.e(TAG, "listen() failed", e);
  159.             }
  160.             mmServerSocket = tmp;
  161.         }

  162.         public void run() {
  163.             if (D) Log.d(TAG, "BEGIN mAcceptThread" + this);
  164.             setName("AcceptThread");
  165.             BluetoothSocket socket = null;

  166.             while (mState != STATE_CONNECTED) {
  167.                 try {
  168.                     socket = mmServerSocket.accept();
  169.                 } catch (IOException e) {
  170.                     Log.e(TAG, "accept() 失敗", e);
  171.                     break;
  172.                 }

  173.                 // 如果連接被接受
  174.                 if (socket != null) {
  175.                     synchronized (BluetoothChatService.this) {
  176.                         switch (mState) {
  177.                         case STATE_LISTEN:
  178.                         case STATE_CONNECTING:
  179.                             // 開始連接線程
  180.                             connected(socket, socket.getRemoteDevice());
  181.                             break;
  182.                         case STATE_NONE:
  183.                         case STATE_CONNECTED:
  184.                             // 沒有準(zhǔn)備好或已經(jīng)連接
  185.                             try {
  186.                                 socket.close();
  187.                             } catch (IOException e) {
  188.                                 Log.e(TAG, "不能關(guān)閉這些連接", e);
  189.                             }
  190.                             break;
  191.                         }
  192.                     }
  193.                 }
  194.             }
  195.             if (D) Log.i(TAG, "結(jié)束mAcceptThread");
  196.         }

  197.         public void cancel() {
  198.             if (D) Log.d(TAG, "取消 " + this);
  199.             try {
  200.                 mmServerSocket.close();
  201.             } catch (IOException e) {
  202.                 Log.e(TAG, "關(guān)閉失敗", e);
  203.             }
  204.         }
  205.     }


  206.     private class ConnectThread extends Thread {
  207.         private final BluetoothSocket mmSocket;
  208.         private final BluetoothDevice mmDevice;

  209.         public ConnectThread(BluetoothDevice device) {
  210.             mmDevice = device;
  211.             BluetoothSocket tmp = null;

  212.             try {
  213.                 tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
  214.             } catch (IOException e) {
  215.                 Log.e(TAG, "create() 失敗", e);
  216.             }
  217.             mmSocket = tmp;
  218.         }

  219.         public void run() {
  220.             Log.i(TAG, "開始mConnectThread");
  221.             setName("ConnectThread");

  222.             mAdapter.cancelDiscovery();

  223.             try {
  224.                 mmSocket.connect();
  225.             } catch (IOException e) {
  226.                 connectionFailed();
  227.                 try {
  228.                     mmSocket.close();
  229.                 } catch (IOException e2) {
  230.                     Log.e(TAG, "關(guān)閉連接失敗", e2);
  231.                 }
  232.                 BluetoothChatService.this.start();
  233.                 return;
  234.             }

  235.             synchronized (BluetoothChatService.this) {
  236.                 mConnectThread = null;
  237.             }

  238.             connected(mmSocket, mmDevice);
  239.         }

  240.         public void cancel() {
  241.             try {
  242.                 mmSocket.close();
  243.             } catch (IOException e) {
  244.                 Log.e(TAG, "關(guān)閉連接失敗", e);
  245.             }
  246.         }
  247.     }

  248.     /**
  249.      * 處理所有傳入和傳出的傳輸
  250.      */
  251.     private class ConnectedThread extends Thread {
  252.         private final BluetoothSocket mmSocket;
  253.         private final InputStream mmInStream;
  254.         private final OutputStream mmOutStream;

  255.         public ConnectedThread(BluetoothSocket socket) {
  256.             Log.d(TAG, "創(chuàng)建 ConnectedThread");
  257.             mmSocket = socket;
  258.             InputStream tmpIn = null;
  259.             OutputStream tmpOut = null;

  260.             // 得到BluetoothSocket輸入和輸出流
  261.             try {
  262.                 tmpIn = socket.getInputStream();
  263.                 tmpOut = socket.getOutputStream();
  264.             } catch (IOException e) {
  265.                 Log.e(TAG, "temp sockets not created", e);
  266.             }

  267.             mmInStream = tmpIn;
  268.             mmOutStream = tmpOut;
  269.         }

  270.         public void run() {
  271.             Log.i(TAG, "BEGIN mConnectedThread");
  272.             int bytes;
  273.             String str1 = "";            
  274.             // 循環(huán)監(jiān)聽消息
  275.             while (true) {
  276.                 try {
  277.                         byte[] buffer = new byte[256];
  278.                         
  279.                     bytes = mmInStream.read(buffer);                    
  280.                     String readStr = new String(buffer, 0, bytes);
  281.                     String str = bytes2HexString(buffer).replaceAll("00","").trim();
  282.                     if(bytes>0)
  283.                     {
  284.                            
  285.                             if (str.endsWith("0D")) {
  286.                                     byte[] buffer1 = (str1+readStr).getBytes();
  287.                                     mHandler.obtainMessage(BluetoothChatActivity.MESSAGE_READ, buffer1.length, -1, buffer1)
  288.                             .sendToTarget();
  289.                                     str1 = "";
  290.                                                 }
  291.                             else{
  292.                                     if (!str.contains("0A")) {
  293.                                             str1 = str1+readStr;
  294.                                                         }else{
  295.                                                                 if (!str.equals("0A")&&str.endsWith("0A")) {
  296.                                                                         mHandler.obtainMessage(BluetoothChatActivity.MESSAGE_READ, bytes, -1, buffer)
  297.                                             .sendToTarget();
  298.                                                                 }
  299.                                                         }
  300.                                                 }
  301.                            
  302.                     }
  303.                     else
  304.                     {
  305.                         Log.e(TAG, "disconnected");
  306.                         connectionLost();
  307.                         
  308.                         if(mState != STATE_NONE)
  309.                         {
  310.                             Log.e(TAG, "disconnected");
  311.                                 BluetoothChatService.this.start();
  312.                         }
  313.                         break;
  314.                     }
  315.                 } catch (IOException e) {
  316.                     Log.e(TAG, "disconnected", e);
  317.                     connectionLost();
  318.                     
  319.                     if(mState != STATE_NONE)
  320.                     {
  321.                             // 在重新啟動監(jiān)聽模式啟動該服務(wù)
  322.                             BluetoothChatService.this.start();
  323.                     }
  324.                     break;
  325.                 }
  326.             }
  327.         }

  328.         /**
  329.          * 寫入OutStream連接
  330.          * @param buffer  要寫的字節(jié)
  331.          */
  332.         public void write(byte[] buffer) {
  333.             try {
  334.                 mmOutStream.write(buffer);

  335.                 // 把消息傳給UI
  336.                 mHandler.obtainMessage(BluetoothChatActivity.MESSAGE_WRITE, -1, -1, buffer)
  337.                         .sendToTarget();
  338.             } catch (IOException e) {
  339.                 Log.e(TAG, "Exception during write", e);
  340.             }
  341.         }

  342.         public void cancel() {
  343.             try {
  344.                 mmSocket.close();
  345.             } catch (IOException e) {
  346.                 Log.e(TAG, "close() of connect socket failed", e);
  347.             }
  348.         }
  349.     }
  350.     /**
  351.      * 從字節(jié)數(shù)組到十六進制字符串轉(zhuǎn)換
  352.      */
  353.     public static String bytes2HexString(byte[] b) {
  354.             String ret = "";
  355.             for (int i = 0; i < b.length; i++) {
  356.              String hex = Integer.toHexString(b[ i ] & 0xFF);
  357.              if (hex.length() == 1) {
  358.               hex = '0' + hex;
  359.              }
  360.              ret += hex.toUpperCase();
  361.             }
  362.             return ret;
  363.           }
  364. }
復(fù)制代碼


回復(fù)

使用道具 舉報

ID:422379 發(fā)表于 2018-11-7 15:24 | 顯示全部樓層
回復(fù)

使用道具 舉報

您需要登錄后才可以回帖 登錄 | 立即注冊

本版積分規(guī)則

手機版|小黑屋|51黑電子論壇 |51黑電子論壇6群 QQ 管理員QQ:125739409;技術(shù)交流QQ群281945664

Powered by 單片機教程網(wǎng)

快速回復(fù) 返回頂部 返回列表