手把手教你Android手机与BLE终端通信--连接,发送和接收数据

From:http://blog.csdn.net/dandan_dany/article/details/51768390

    如果你还没有看上一篇 手把手教你Android手机与BLE终端通信--搜索,你就先看看吧,因为这一篇要接着讲搜索到蓝牙后的连接,和连接后的发送和接收数据。


    评论里有很多人问如果一条信息特别长,怎么不丢包,或者怎么判断一个完整的信息发送完了呢。我写的时候连的串口是我们公司硬件工程师设计的,他定义好了信息的格式,什么字符开头,什么字符结尾,中间哪几位代表什么意思,我如果不能成功取到一对开头和结尾并且长度也符合我就会丢弃那点信息,取得的完整信息则会根据硬件工程师的文档取出app相应地方用到的相应信息,嗯,就是这样。如果你不知道一个串口发给你什么信息,那一定是你拿来玩的串口,工作中用到的都是定制的,不然连接串口干什么呢。

    我的基本实现就是所有蓝牙操作都写在BluetoothController中,他有消息要发送时发送到BLEService中,service再发广播提示MainActivity更新页面。好了,切入正题。。

    1,连接

    首先点击搜索到的蓝牙的listview,连接点击的那个蓝牙:

[html]  view plain  copy
  1. listview.setOnItemClickListener(new OnItemClickListener() {  
  2.   
  3.             @Override  
  4.             public void onItemClick(AdapterView<?> arg0, View arg1, int index,  
  5.                     long arg3) {  
  6.                 BluetoothController.getInstance().connect(list.get(index));  
  7.             }  
  8.         });  
connect方法仍然写在controller中,那个与蓝牙控制类。
[html]  view plain  copy
  1. /**  
  2.      * 连接蓝牙设备  
  3.      *   
  4.      * @param device  
  5.      *            待连接的设备  
  6.      */  
  7.     public void connect(EntityDevice device) {  
  8.         deviceAddress=device.getAddress();  
  9.         deviceName=device.getName();  
  10.         BluetoothDevice localBluetoothDevice = bleAdapter  
  11.                 .getRemoteDevice(device.getAddress());  
  12.         if (bleGatt != null) {  
  13.   
  14.             bleGatt.disconnect();  
  15.             bleGatt.close();  
  16.             bleGatt = null;  
  17.         }  
  18.         bleGatt = localBluetoothDevice.connectGatt(App.app, false,  
  19.                 bleGattCallback);  
  20.     }  
bleGatt是与蓝牙沟通的控制类,系统自带的BluetoothGatt类,它可以连接,断开某设备,或者获取服务,写数据。蓝牙有很多服务,但我们要找那个可读写的服务,下面会有查找服务。

你应该注意到bleGattCallback,BluetoothGattCallback,也是系统自带的类,是连接回调类,连接后出现什么情况怎么处理就在这里了。它有很多方法需要重写,我们只重写两三个。关于连接我们需要重写的是onConnectionStateChange(BluetoothGatt paramAnonymousBluetoothGatt, int oldStatus,int newStatus),第一个参数不用管,我也不知道是什么,第二个参数是原来的状态,第三个参数是后来的状态,这本来就是状态改变回调方法嘛。对了,0表示未连接上,2表示已连接设备。当成功连接后我们要更新界面,未连接也要更新,因为可能是连接过程中意外中断,也可能有意中断,提醒下亲爱的用户还是比较好的。

[html]  view plain  copy
  1. /**  
  2.          * 连接状态改变  
  3.          */  
  4.         public void onConnectionStateChange(  
  5.                 BluetoothGatt paramAnonymousBluetoothGatt, int oldStatus,  
  6.                 int newStatus) {  
  7.             if (newStatus == 2)// 已连接状态,表明连接成功  
  8.             {  
  9.                 Message msg=new Message();  
  10.                 msg.what=ConstantUtils.WM_BLE_CONNECTED_STATE_CHANGE;  
  11.                 Bundle bundle=new Bundle();  
  12.                 bundle.putString("address", deviceAddress);  
  13.                 bundle.putString("name", deviceName);  
  14.                 msg.obj=bundle;  
  15.                 serviceHandler.sendMessage(msg);  
  16.                 paramAnonymousBluetoothGatt.discoverServices();  
  17.                 //连接到蓝牙后查找可以读写的服务,蓝牙有很多服务  
  18.                 return;  
  19.             }  
  20.             if (newStatus == 0)// 断开连接或未连接成功  
  21.             {  
  22.                 serviceHandler.sendEmptyMessage(ConstantUtils.WM_STOP_CONNECT);  
  23.                 return;  
  24.             }  
  25.             paramAnonymousBluetoothGatt.disconnect();  
  26.             paramAnonymousBluetoothGatt.close();  
  27.             return;  
  28.         }  
这样连接状态改变的消息就发到了service, service接收到消息后发广播提醒界面更新

[html]  view plain  copy
  1. Handler handler = new Handler() {  
  2.         public void handleMessage(android.os.Message msg) {  
  3.             switch (msg.what) {  
  4.             case ConstantUtils.WM_BLE_CONNECTED_STATE_CHANGE:// 连接上某个设备的消息  
  5.                 Bundle bundle = (Bundle) msg.obj;  
  6.                 String address = bundle.getString("address");  
  7.                 String name = bundle.getString("name");  
  8.                 // 连接状态改变广播  
  9.                 Bundle bundle1 = new Bundle();  
  10.                 bundle1.putString("address", address);  
  11.                 bundle1.putString("name", name);  
  12.                 Intent intentDevice = new Intent(  
  13.                         ConstantUtils.ACTION_CONNECTED_ONE_DEVICE);  
  14.                 intentDevice.putExtras(bundle1);  
  15.                 sendBroadcast(intentDevice);  
  16.                 break;  
  17.   
  18.             case ConstantUtils.WM_STOP_CONNECT:  
  19.                 Intent stopConnect = new Intent(  
  20.                         ConstantUtils.ACTION_STOP_CONNECT);  
  21.                 sendBroadcast(stopConnect);  
  22.                 break;  

然后主界面MainActivity接收到广播后更新页面。如果是连接就把连接的设备地址打印出来,如果是断开了,就清除打印并且弹一个toast.当然这些代码在一个receiver中。

[html]  view plain  copy
  1. else if (intent.getAction().equalsIgnoreCase(ConstantUtils.ACTION_CONNECTED_ONE_DEVICE)){  
  2.                 connectedDevice.setText("连接的蓝牙是:"+intent.getStringExtra("address"));  
  3.             }  
  4.               
  5.             else if (intent.getAction().equalsIgnoreCase(ConstantUtils.ACTION_STOP_CONNECT)){  
  6.                 connectedDevice.setText("");  
  7.                 toast("连接已断开");  
  8.             }  
为了测试断开,我关了蓝牙,你可以试试。


2,接收数据

  首先你需要下载一个串口助手,可以看到串口接收到的数据,也可以通过串口发送数据到跟他连接的设备。

  查看接收到的数据只需要重写上面串口回调BluetoothGattCallback的一个方法,public void onCharacteristicChanged(BluetoothGatt paramAnonymousBluetoothGatt,  BluetoothGattCharacteristic paramAnonymousBluetoothGattCharacteristic) 

[html]  view plain  copy
  1. /**  
  2.      * 与蓝牙通信回调  
  3.      */  
  4.     public BluetoothGattCallback bleGattCallback = new BluetoothGattCallback() {  
  5.         /**  
  6.          * 收到消息  
  7.          */  
  8.         public void onCharacteristicChanged(  
  9.                 BluetoothGatt paramAnonymousBluetoothGatt,  
  10.                 BluetoothGattCharacteristic paramAnonymousBluetoothGattCharacteristic) {  
  11.   
  12.             byte[] arrayOfByte = paramAnonymousBluetoothGattCharacteristic  
  13.                     .getValue();  
  14.             if(BluetoothController.this.serviceHandler!=null){  
  15.                 Message msg=new Message();  
  16.                 msg.what=ConstantUtils.WM_RECEIVE_MSG_FROM_BLE;  
  17.                 //byte数组转换为十六进制字符串  
  18.                 msg.obj=ConvertUtils.getInstance().bytesToHexString(arrayOfByte);  
  19.                 BluetoothController.this.serviceHandler.sendMessage(msg);  
  20.             }  
  21.             //也可以先打印出来看看  
  22.             Log.i("TEST",ConvertUtils.getInstance().bytesToHexString(arrayOfByte));  
  23.         }  
接下来的操作还是一样,接受到数据发消息到service,service发广播更新到activity界面。

byteToHexString是把byte数组转化成16进制的数值的字符串。

3,发送数据

在输入框上填入要发送的数据,点按钮发送数据

[html]  view plain  copy
  1. btnSend.setOnClickListener(new OnClickListener() {  
  2.               
  3.             @Override  
  4.             public void onClick(View arg0) {  
  5.                 String str=editSend.getText().toString();  
  6.                 if(str!=null&&str.length()>0){  
  7.                     controller.write(str.getBytes());  
  8.                 }  
  9.                 else {  
  10.                     toast("请填上要发送的内容");  
  11.                 }  
  12.                   
  13.             }  
  14.         });  
发送方法也在controller中

[html]  view plain  copy
  1. /**  
  2.      * 传输数据  
  3.      *   
  4.      * @param byteArray  
  5.      * @return  
  6.      */  
  7.     public boolean write(byte byteArray[]) {  
  8.         if (bleGattCharacteristic == null)  
  9.             return false;  
  10.         if (bleGatt == null)  
  11.             return false;  
  12.         bleGattCharacteristic.setValue(byteArray);  
  13.         return bleGatt.writeCharacteristic(bleGattCharacteristic);  
  14.     }  
  15.   
  16.     /**  
  17.      * 传输数据  
  18.      *   
  19.      * @param byteArray  
  20.      * @return  
  21.      */  
  22.     public boolean write(String str) {  
  23.         if (bleGattCharacteristic == null)  
  24.             return false;  
  25.         if (bleGatt == null)  
  26.             return false;  
  27.         bleGattCharacteristic.setValue(str);  
  28.         return bleGatt.writeCharacteristic(bleGattCharacteristic);  
  29.     }  
这里又用来了一个新类,BluetoothGattCharacteristic,他封装了要发送数据,通过bleGatt发送就可以了,bleGatt管的就是连接,断开连接和发送。

最后,一定不要忘了蓝牙的服务,蓝牙有很多服务,要找到我们要的,你怎么知道要那个服务呢,把每个服务的属性都打印出来,你就发现只有一个服务的属性是可读可写的,找到它赋值给数据封装类bleGattCharacteristic就行了。

重写回调的onServicesDiscovered(BluetoothGatt paramAnonymousBluetoothGatt, int paramAnonymousInt)方法发现服务。

[html]  view plain  copy
  1. public void onServicesDiscovered(  
  2.                 BluetoothGatt paramAnonymousBluetoothGatt, int paramAnonymousInt) {  
  3.             BluetoothController.this.findService(paramAnonymousBluetoothGatt  
  4.                     .getServices());  
  5.         }  

[html]  view plain  copy
  1. /**  
  2.  * 搜索服务  
  3.  *   
  4.  * @param paramList  
  5.  */  
  6. public void findService(List<BluetoothGattService> paramList) {  
  7.   
  8.     Iterator localIterator1 = paramList.iterator();  
  9.     while (localIterator1.hasNext()) {  
  10.         BluetoothGattService localBluetoothGattService = (BluetoothGattService) localIterator1  
  11.                 .next();  
  12.         if (localBluetoothGattService.getUuid().toString()  
  13.                 .equalsIgnoreCase(ConstantUtils.UUID_SERVER)) {  
  14.             List localList = localBluetoothGattService.getCharacteristics();  
  15.             Iterator localIterator2 = localList.iterator();  
  16.             while (localIterator2.hasNext()) {  
  17.                 BluetoothGattCharacteristic localBluetoothGattCharacteristic = (BluetoothGattCharacteristic) localIterator2  
  18.                         .next();  
  19.                 if (localBluetoothGattCharacteristic.getUuid().toString()  
  20.                         .equalsIgnoreCase(ConstantUtils.UUID_NOTIFY)) {  
  21.                     bleGattCharacteristic = localBluetoothGattCharacteristic;  
  22.                     break;  
  23.                 }  
  24.             }  
  25.             break;  
  26.         }  
  27.   
  28.     }  
  29.   
  30.     bleGatt.setCharacteristicNotification(bleGattCharacteristic, true);  
  31. }  

服务号:

[html]  view plain  copy
  1. public final static  String UUID_SERVER="0000ffe0-0000-1000-8000-00805f9b34fb";  
  2.         public final static  String UUID_NOTIFY="0000ffe1-0000-1000-8000-00805f9b34fb";  

到哪儿都一样。


如果你看到这儿了,恭喜你,下面都是必备干货:

代码就是这样,包括上次的搜索都在下面的连接里,里面有.apk文件,你先跑跑看效果,还有串口助手exe文件,还有es里的代码,还有串口怎样使用,怎样配置,我真是太贴心了吐舌头

http://pan.baidu.com/s/1geCKYJL

(不要忘了在manifest中加一个权限,为了兼容6.0以上手机:

<uses-permission-sdk-23 android:name="android.permission.ACCESS_COARSE_LOCATION"/>

对了,前几篇文章怎么没人拍砖呢,让我看看哪里不对了好改呀,实在找不到不对的,怎么也没人说句好听的呢?总之,怎么一点互动都没有呢难过,唉。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值