Android提高之Android手机与BLE终端通信

最近穿戴设备发展得很火,把相关技术也带旺了,其中一项是BLE(Bluetooth Low Energy)。BLE是蓝牙4.0的核心Profile,主打功能是快速搜索,快速连接,超低功耗保持连接和传输数据,弱点是数据传输速率低,由于BLE的低功耗特点,因此普遍用于穿戴设备。Android 4.3才开始支持BLE API,所以请各位客官把本文代码运行在蓝牙4.0和Android 4.3及其以上的系统,另外本文所用的BLE终端是一个蓝牙4.0的串口蓝牙模块。

注:笔者的i9100刷了4.4系统后,竟然也能跟BLE蓝牙模块通信。

BLE分为三部分Service、Characteristic、Descriptor,这三部分都由UUID作为唯一标示符。一个蓝牙4.0的终端可以包含多个Service,一个Service可以包含多个Characteristic,一个Characteristic包含一个Value和多个Descriptor,一个Descriptor包含一个Value。一般来说,Characteristic是手机与BLE终端交换数据的关键,Characteristic有较多的跟权限相关的字段,例如PERMISSION和PROPERTY,而其中最常用的是PROPERTY,本文所用的BLE蓝牙模块竟然没有标准的Characteristic的PERMISSION。Characteristic的PROPERTY可以通过位运算符组合来设置读写属性,例如READ|WRITE、READ|WRITE_NO_RESPONSE|NOTIFY,因此读取PROPERTY后要分解成所用的组合(本文代码已含此分解方法)。

本文代码改自Android 4.3 Sample的BluetoothLeGatt,把冗余代码去掉,获取的BLE设备信息都通过Log,还有一些必要的读写蓝牙方法,应该算是简化到大家一看就可以懂了。本文完整代码可以点击此处本站下载。

接下来贴出本文运行的结果,首先是连接BLE设备后,枚举出设备所有Service、Characteristic、Descriptor,并且手机会往Characteristic uuid=0000ffe1-0000-1000-8000-00805f9b34fb写入“send data->”字符串,BLE终端收到数据通过串口传到PC串口助手:
04-21 18:28:25.465: E/DeviceScanActivity(12254): -->service type:PRIMARY
04-21 18:28:25.465: E/DeviceScanActivity(12254): -->includedServices size:0
04-21 18:28:25.465: E/DeviceScanActivity(12254): -->service uuid:00001800-0000-1000-8000-00805f9b34fb
04-21 18:28:25.465: E/DeviceScanActivity(12254): ---->char uuid:00002a00-0000-1000-8000-00805f9b34fb
04-21 18:28:25.465: E/DeviceScanActivity(12254): ---->char permission:UNKNOW
04-21 18:28:25.465: E/DeviceScanActivity(12254): ---->char property:READ
04-21 18:28:25.465: E/DeviceScanActivity(12254): ---->char uuid:00002a01-0000-1000-8000-00805f9b34fb
04-21 18:28:25.470: E/DeviceScanActivity(12254): ---->char permission:UNKNOW
04-21 18:28:25.470: E/DeviceScanActivity(12254): ---->char property:READ
04-21 18:28:25.470: E/DeviceScanActivity(12254): ---->char uuid:00002a02-0000-1000-8000-00805f9b34fb
04-21 18:28:25.470: E/DeviceScanActivity(12254): ---->char permission:UNKNOW
04-21 18:28:25.470: E/DeviceScanActivity(12254): ---->char property:READ|WRITE|
04-21 18:28:25.470: E/DeviceScanActivity(12254): ---->char uuid:00002a03-0000-1000-8000-00805f9b34fb
04-21 18:28:25.470: E/DeviceScanActivity(12254): ---->char permission:UNKNOW
04-21 18:28:25.475: E/DeviceScanActivity(12254): ---->char property:READ|WRITE|
04-21 18:28:25.475: E/DeviceScanActivity(12254): ---->char uuid:00002a04-0000-1000-8000-00805f9b34fb
04-21 18:28:25.475: E/DeviceScanActivity(12254): ---->char permission:UNKNOW
04-21 18:28:25.475: E/DeviceScanActivity(12254): ---->char property:READ
04-21 18:28:25.475: E/DeviceScanActivity(12254): -->service type:PRIMARY
04-21 18:28:25.475: E/DeviceScanActivity(12254): -->includedServices size:0
04-21 18:28:25.475: E/DeviceScanActivity(12254): -->service uuid:00001801-0000-1000-8000-00805f9b34fb
04-21 18:28:25.480: E/DeviceScanActivity(12254): ---->char uuid:00002a05-0000-1000-8000-00805f9b34fb
04-21 18:28:25.480: E/DeviceScanActivity(12254): ---->char permission:UNKNOW
04-21 18:28:25.480: E/DeviceScanActivity(12254): ---->char property:INDICATE
04-21 18:28:25.480: E/DeviceScanActivity(12254): -------->desc uuid:00002902-0000-1000-8000-00805f9b34fb
04-21 18:28:25.480: E/DeviceScanActivity(12254): -------->desc permission:UNKNOW
04-21 18:28:25.480: E/DeviceScanActivity(12254): -->service type:PRIMARY
04-21 18:28:25.480: E/DeviceScanActivity(12254): -->includedServices size:0
04-21 18:28:25.480: E/DeviceScanActivity(12254): -->service uuid:0000ffe0-0000-1000-8000-00805f9b34fb
04-21 18:28:25.480: E/DeviceScanActivity(12254): ---->char uuid:0000ffe1-0000-1000-8000-00805f9b34fb
04-21 18:28:25.480: E/DeviceScanActivity(12254): ---->char permission:UNKNOW
04-21 18:28:25.480: E/DeviceScanActivity(12254): ---->char property:READ|WRITE_NO_RESPONSE|NOTIFY|
04-21 18:28:25.490: E/DeviceScanActivity(12254): -------->desc uuid:00002902-0000-1000-8000-00805f9b34fb
04-21 18:28:25.490: E/DeviceScanActivity(12254): -------->desc permission:UNKNOW
04-21 18:28:25.490: E/DeviceScanActivity(12254): -------->desc uuid:00002901-0000-1000-8000-00805f9b34fb
04-21 18:28:25.490: E/DeviceScanActivity(12254): -------->desc permission:UNKNOW
04-21 18:28:26.025: E/DeviceScanActivity(12254): onCharRead BLE DEVICE read 0000ffe1-0000-1000-8000-00805f9b34fb -> 00
这里红字是由BluetoothGattCallback的onCharacteristicRead()回调而打出Log

以下Log是PC上的串口工具通过BLE模块发送过来,由BluetoothGattCallback的 onCharacteristicChanged()打出Log
04-21 18:30:18.260: E/DeviceScanActivity(12254): onCharWrite BLE DEVICE write 0000ffe1-0000-1000-8000-00805f9b34fb -> send data to phone
04-21 18:30:18.745: E/DeviceScanActivity(12254): onCharWrite BLE DEVICE write 0000ffe1-0000-1000-8000-00805f9b34fb -> send data to phone
04-21 18:30:19.085: E/DeviceScanActivity(12254): onCharWrite BLE DEVICE write 0000ffe1-0000-1000-8000-00805f9b34fb -> send data to phone
04-21 18:30:19.350: E/DeviceScanActivity(12254): onCharWrite BLE DEVICE write 0000ffe1-0000-1000-8000-00805f9b34fb -> send data to phone
04-21 18:30:19.605: E/DeviceScanActivity(12254): onCharWrite BLE DEVICE write 0000ffe1-0000-1000-8000-00805f9b34fb -> send data to phone
04-21 18:30:19.835: E/DeviceScanActivity(12254): onCharWrite BLE DEVICE write 0000ffe1-0000-1000-8000-00805f9b34fb -> send data to phone
04-21 18:30:20.055: E/DeviceScanActivity(12254): onCharWrite BLE DEVICE write 0000ffe1-0000-1000-8000-00805f9b34fb -> send data to phone
04-21 18:30:20.320: E/DeviceScanActivity(12254): onCharWrite BLE DEVICE write 0000ffe1-0000-1000-8000-00805f9b34fb -> send data to phone
04-21 18:30:20.510: E/DeviceScanActivity(12254): onCharWrite BLE DEVICE write 0000ffe1-0000-1000-8000-00805f9b34fb -> send data to phone
04-21 18:30:20.735: E/DeviceScanActivity(12254): onCharWrite BLE DEVICE write 0000ffe1-0000-1000-8000-00805f9b34fb -> send data to phone
04-21 18:30:21.000: E/DeviceScanActivity(12254): onCharWrite BLE DEVICE write 0000ffe1-0000-1000-8000-00805f9b34fb -> send data to phone

接下来贴出本文核心代码:

public class DeviceScanActivity extends ListActivity {
 private final static String TAG = DeviceScanActivity.class.getSimpleName();
 private final static String UUID_KEY_DATA = "0000ffe1-0000-1000-8000-00805f9b34fb";

  private LeDeviceListAdapter mLeDeviceListAdapter;
  /**搜索BLE终端*/
  private BluetoothAdapter mBluetoothAdapter;
  /**读写BLE终端*/
  private BluetoothLeClass mBLE;
  private boolean mScanning;
  private Handler mHandler;

  // Stops scanning after 10 seconds.
  private static final long SCAN_PERIOD = 10000;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getActionBar().setTitle(R.string.title_devices);
    mHandler = new Handler();
    // Use this check to determine whether BLE is supported on the device. Then you can
    // selectively disable BLE-related features.
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
      Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
      finish();
    }
    // Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
    // BluetoothAdapter through BluetoothManager.
    final BluetoothManager bluetoothManager =
        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();
    // Checks if Bluetooth is supported on the device.
    if (mBluetoothAdapter == null) {
      Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
      finish();
      return;
    }
    //开启蓝牙
    mBluetoothAdapter.enable();
    mBLE = new BluetoothLeClass(this);
    if (!mBLE.initialize()) {
      Log.e(TAG, "Unable to initialize Bluetooth");
      finish();
    }
    //发现BLE终端的Service时回调
    mBLE.setOnServiceDiscoverListener(mOnServiceDiscover);
    //收到BLE终端数据交互的事件
    mBLE.setOnDataAvailableListener(mOnDataAvailable);
  }
  @Override
  protected void onResume() {
    super.onResume();

    // Initializes list view adapter.
    mLeDeviceListAdapter = new LeDeviceListAdapter(this);
    setListAdapter(mLeDeviceListAdapter);
    scanLeDevice(true);
  }
  @Override
  protected void onPause() {
    super.onPause();
    scanLeDevice(false);
    mLeDeviceListAdapter.clear();
    mBLE.disconnect();
  }
  @Override
  protected void onStop() {
    super.onStop();
    mBLE.close();
  }
  @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
    final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
    if (device == null) return;
    if (mScanning) {
      mBluetoothAdapter.stopLeScan(mLeScanCallback);
      mScanning = false;
    }
    mBLE.connect(device.getAddress());
  }
  private void scanLeDevice(final boolean enable) {
    if (enable) {
      // Stops scanning after a pre-defined scan period.
      mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
          mScanning = false;
          mBluetoothAdapter.stopLeScan(mLeScanCallback);
          invalidateOptionsMenu();
        }
      }, SCAN_PERIOD);
      mScanning = true;
      mBluetoothAdapter.startLeScan(mLeScanCallback);
    } else {
      mScanning = false;
      mBluetoothAdapter.stopLeScan(mLeScanCallback);
    }
    invalidateOptionsMenu();
  }
  /**
   * 搜索到BLE终端服务的事件
   */
  private BluetoothLeClass.OnServiceDiscoverListener mOnServiceDiscover = new OnServiceDiscoverListener(){

 @Override
 public void onServiceDiscover(BluetoothGatt gatt) {
  displayGattServices(mBLE.getSupportedGattServices());
 }
  };
  /**
   * 收到BLE终端数据交互的事件
   */
  private BluetoothLeClass.OnDataAvailableListener mOnDataAvailable = new OnDataAvailableListener(){
   /**
   * BLE终端数据被读的事件
   */
 @Override
 public void onCharacteristicRead(BluetoothGatt gatt,
  BluetoothGattCharacteristic characteristic, int status) {
  if (status == BluetoothGatt.GATT_SUCCESS)
  Log.e(TAG,"onCharRead "+gatt.getDevice().getName()
   +" read "
   +characteristic.getUuid().toString()
   +" -> "
   +Utils.bytesToHexString(characteristic.getValue()));
 }
   /**
   * 收到BLE终端写入数据回调
   */
 @Override
 public void onCharacteristicWrite(BluetoothGatt gatt,
  BluetoothGattCharacteristic characteristic) {
  Log.e(TAG,"onCharWrite "+gatt.getDevice().getName()
   +" write "
   +characteristic.getUuid().toString()
   +" -> "
   +new String(characteristic.getValue()));
 }
  };
  // Device scan callback.
  private BluetoothAdapter.LeScanCallback mLeScanCallback =
      new BluetoothAdapter.LeScanCallback() {
    @Override
    public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
      runOnUiThread(new Runnable() {
        @Override
        public void run() {
          mLeDeviceListAdapter.addDevice(device);
          mLeDeviceListAdapter.notifyDataSetChanged();
        }
      });
    }
  };
  private void displayGattServices(List<BluetoothGattService> gattServices) {
    if (gattServices == null) return;
    for (BluetoothGattService gattService : gattServices) {
     //-----Service的字段信息-----//
     int type = gattService.getType();
      Log.e(TAG,"-->service type:"+Utils.getServiceType(type));
      Log.e(TAG,"-->includedServices size:"+gattService.getIncludedServices().size());
      Log.e(TAG,"-->service uuid:"+gattService.getUuid());

      //-----Characteristics的字段信息-----//
      List<BluetoothGattCharacteristic> gattCharacteristics =gattService.getCharacteristics();
      for (final BluetoothGattCharacteristic gattCharacteristic: gattCharacteristics) {
        Log.e(TAG,"---->char uuid:"+gattCharacteristic.getUuid());
        int permission = gattCharacteristic.getPermissions();
        Log.e(TAG,"---->char permission:"+Utils.getCharPermission(permission));
        int property = gattCharacteristic.getProperties();
        Log.e(TAG,"---->char property:"+Utils.getCharPropertie(property));
        byte[] data = gattCharacteristic.getValue();
     if (data != null && data.length > 0) {
      Log.e(TAG,"---->char value:"+new String(data));
     }
     //UUID_KEY_DATA是可以跟蓝牙模块串口通信的Characteristic
     if(gattCharacteristic.getUuid().toString().equals(UUID_KEY_DATA)){
      //测试读取当前Characteristic数据,会触发mOnDataAvailable.onCharacteristicRead()
      mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
             mBLE.readCharacteristic(gattCharacteristic);
            }
          }, 500);
      //接受Characteristic被写的通知,收到蓝牙模块的数据后会触发mOnDataAvailable.onCharacteristicWrite()
      mBLE.setCharacteristicNotification(gattCharacteristic, true);
      //设置数据内容
      gattCharacteristic.setValue("send data->");
      //往蓝牙模块写入数据
      mBLE.writeCharacteristic(gattCharacteristic);
     }
     //-----Descriptors的字段信息-----//
  List<BluetoothGattDescriptor> gattDescriptors = gattCharacteristic.getDescriptors();
  for (BluetoothGattDescriptor gattDescriptor : gattDescriptors) {
   Log.e(TAG, "-------->desc uuid:" + gattDescriptor.getUuid());
   int descPermission = gattDescriptor.getPermissions();
   Log.e(TAG,"-------->desc permission:"+ Utils.getDescPermission(descPermission));
   byte[] desData = gattDescriptor.getValue();
   if (desData != null && desData.length > 0) {
   Log.e(TAG, "-------->desc value:"+ new String(desData));
   }
      }
      }
    }//
  }
}

感兴趣的读者可以动手测试一下代码的运行情况,希望能对大家的Android项目开发有所帮助。

(0)

相关推荐

  • android开发之调用手机的摄像头使用MediaRecorder录像并播放

    我们玩玩手机的录像功能吧.做个DEMO. 看看录制过程: 复制代码 代码如下: mediarecorder = new MediaRecorder();// 创建mediarecorder对象 // 设置录制视频源为Camera(相机) mediarecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); // 设置录制完成后视频的封装格式THREE_GPP为3gp.MPEG_4为mp4 mediarecorder.setOutputFo

  • Android如何通过手机获取验证码来完成注册功能

    注册很多app或者网络账户的时候,经常需要手机获取验证码,来完成注册,那时年少,只是觉得手机获取验证码这件事儿很好玩,并没有关心太多,她是如何实现的,以及她背后的故事到底是什么样子的,现在小编接手的这个项目里面,就需要通过手机号进行注册,并且手机号发送相应的验证码,来完成注册,那么在一些应用app里面到底是如何实现点击按钮获取验证码,来完成注册这整个流程的呢?今天小编就以注册为例,和小伙伴们分享一下,如何通过手机号获取验证码来完成注册的一整套流程以及如何采用正则表达式来验证手机号码是否符合电信.

  • Android获取手机位置的实现代码

    本文实例为大家分享了Android获取手机位置的方法,供大家参考,具体内容如下 1.项目Src下创建...service包,然后新建GPSService类 package com.zebra.mobilesafe.service; import java.io.IOException; import java.io.InputStream; import android.app.Service; import android.content.Intent; import android.cont

  • Android获取手机型号/系统版本号/App版本号等信息实例讲解

    MainActivity如下: 复制代码 代码如下: package cn.testgethandsetinfo; import android.os.Bundle; import android.text.TextUtils; import android.widget.TextView; import android.app.Activity; import android.content.Context; import android.content.pm.PackageInfo; imp

  • android 手机SD卡读写操作(以txt文本为例)实现步骤

    1.首先对manifest注册SD卡读写权限 要说明一下,我这里没有用MainActivity.class作为软件入口 复制代码 代码如下: AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com

  • js和html5实现手机端刮刮卡抽奖效果完美兼容android/IOS

    绝对值得看的来篇,哈哈.本人亲自完成,有错误请大家指出: 现在的手机完美支持html5,所以如果手机端想要做个抽奖模块的话,用刮刮卡抽奖效果,相信这个互动体验是非常棒的 ​ps:由于本人没有wp8系统的手机,所以没法兼容wp8系统的,目前完美兼容android,IOS 如果要在pc浏览的话,得改下js,目前支持谷歌,火狐,ie>=10,如果网友想要的话我就去写个 代码如下: 复制代码 代码如下: <!DOCTYPE html> <html lang="en"&g

  • android计算pad或手机的分辨率/像素/密度/屏幕尺寸/DPI值的方法

    手机分辨率基础知识(DPI,DIP计算) 1.术语和概念 术语 说明 备注 Screen size(屏幕尺寸) 指的是手机实际的物理尺寸,比如常用的2.8英寸,3.2英寸,3.5英寸,3.7英寸 摩托罗拉milestone手机是3.7英寸 Aspect Ratio(宽高比率) 指的是实际的物理尺寸宽高比率,分为long和nolong Milestone是16:9,属于long Resolution(分辨率) 和电脑的分辨率概念一样,指手机屏幕纵.横方向像素个数 Milestone是854*480

  • js判断手机端(Android手机还是iPhone手机)

    网上常用的代码 /** * [isMobile 判断平台] * @param test: 0:iPhone 1:Android */ function ismobile(test){ var u = navigator.userAgent, app = navigator.appVersion; if(/AppleWebKit.*Mobile/i.test(navigator.userAgent) || (/MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alca

  • 基于JavaScript实现根据手机定位获取当前具体位置(X省X市X县X街道X号)

    废话不多说了,直接给大家贴js代码了.具体代码如下所示: function Location(){}; Location.prototype.getLocation = function(callback){ var options = { enableHighAccuracy: true, maximumAge: 1000 }; this.callback = Object.prototype.toString.call(callback) =="[object Function]"

  • 浅析Android手机卫士之手机实现短信指令获取位置

    推荐阅读: 浅析Android手机卫士sim卡绑定 深入浅析Android手机卫士保存密码时进行md5加密 详解Android 手机卫士设置向导页面 浅析Android手机卫士关闭自动更新 浅析Android手机卫士自定义控件的属性 浅析Android手机卫士读取联系人 浅析Android手机卫士接收短信指令执行相应操作 浅析Android手机卫士手机定位的原理 获取位置 新建一个service的包 新建一个GPSService类继承系统的Service类 清单文件中注册一下 重写onCreat

随机推荐