找回密码
 立即注册

QQ登录

只需一步,快速开始

帖子
查看: 3839|回复: 1
收起左侧

Android蓝牙调试助手源码分享

[复制链接]
ID:420684 发表于 2018-11-4 20:06 | 显示全部楼层 |阅读模式
0.png
下载:
蓝牙调试助手.zip (121.49 KB, 下载次数: 50)

部分源码预览:
  1. package com.example.android.BluetoothChat;
  2. /**
  3. * 描述:蓝牙服务核心类
  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.     // 测试数据
  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.     // 常量,显示当前的连接状态
  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.      * 设置当前的连接状态
  44.      * @param state  连接状态
  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.      * 返回当前连接状态
  54.      *
  55.      */
  56.     public synchronized int getState() {
  57.         return mState;
  58.     }

  59.     /**
  60.      *开始聊天服务
  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.      * 连接远程设备
  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, "无法连接设备");
  135.         msg.setData(bundle);
  136.         mHandler.sendMessage(msg);
  137.     }

  138.     /**
  139.      * 设备断开连接,通知Activity
  140.      */
  141.     private void connectionLost() {

  142.         Message msg = mHandler.obtainMessage(BluetoothChatActivity.MESSAGE_TOAST);
  143.         Bundle bundle = new Bundle();
  144.         bundle.putString(BluetoothChatActivity.TOAST, "设备断开连接");
  145.         msg.setData(bundle);
  146.         mHandler.sendMessage(msg);
  147.     }

  148.     /**
  149.      * 监听传入的连接
  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.                             // 没有准备好或已经连接
  185.                             try {
  186.                                 socket.close();
  187.                             } catch (IOException e) {
  188.                                 Log.e(TAG, "不能关闭这些连接", e);
  189.                             }
  190.                             break;
  191.                         }
  192.                     }
  193.                 }
  194.             }
  195.             if (D) Log.i(TAG, "结束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, "关闭失败", 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, "关闭连接失败", 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, "关闭连接失败", 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, "创建 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.             // 循环监听消息
  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.                             // 在重新启动监听模式启动该服务
  322.                             BluetoothChatService.this.start();
  323.                     }
  324.                     break;
  325.                 }
  326.             }
  327.         }

  328.         /**
  329.          * 写入OutStream连接
  330.          * @param buffer  要写的字节
  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.      * 从字节数组到十六进制字符串转换
  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. }
复制代码


回复

举报

ID:422379 发表于 2018-11-7 15:24 | 显示全部楼层
回复

举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|51黑电子论坛 |51黑电子论坛6群 QQ 管理员QQ:125739409;技术交流QQ群281945664

Powered by 单片机教程网

快速回复 返回顶部 返回列表