蓝牙Ble基础

之前写了一篇关于手机与ble通信的博客
http://blog.csdn.net/z957250254/article/details/52411556
但是估计大家看不怎么懂,没有图只有文字,但是没关系,只要需要做与ble设备的时候再仔细琢磨,就会发现很简单的,所以我这写一篇蓝牙基础的东西,下面也简要的说了下gatt

好进入正题,操作蓝牙首先需要打开蓝牙设备

一、权限:

和经典蓝牙一样,应用使用蓝牙,需要声明BLUETOOTH权限,如果需要扫描设备或者操作蓝牙设置,则还需要BLUETOOTH_ADMIN权限:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

除了蓝牙权限外,如果需要BLE feature则还需要声明uses-feature:

<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>

按时required为true时,则应用只能在支持BLE的Android设备上安装运行;required为false时,Android设备均可正常安装运行,需要在代码运行时判断设备是否支持BLE feature:

public void checkble(){
    // 检查当前手机是否支持ble 蓝牙,如果不支持退出程序
    if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
        finish();
    }
}

二、打开蓝牙

在使用蓝牙BLE之前,需要确认Android设备是否支持BLE feature(required为false时),另外要需要确认蓝牙是否打开。
如果发现不支持BLE,则不能使用BLE相关的功能。如果支持BLE,但是蓝牙没打开,则需要打开蓝牙。

打开蓝牙的步骤:

1、获取BluetoothAdapter

BluetoothAdapter是Android系统中所有蓝牙操作都需要的,它对应本地Android设备的蓝牙模块,在整个系统中BluetoothAdapter是单例的。当你获取到它的示例之后,就能进行相关的蓝牙操作了。

获取BluetoothAdapter代码示例如下:

public void getadapter() {

        // 初始化 Bluetooth adapter, 通过蓝牙管理器得到一个参考蓝牙适配器(API必须在以上android4.3或以上和版本)
        final BluetoothManager bluetoothManager
        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
    }

注:这里通过getSystemService获取BluetoothManager,再通过BluetoothManager获取BluetoothAdapter。BluetoothManager在Android4.3以上支持(API level 18)。

2、判断是否支持蓝牙,并打开蓝牙

获取到BluetoothAdapter之后,还需要判断是否支持蓝牙,以及蓝牙是否打开。
如果没打开,需要让用户打开蓝牙:

 public void startBluetooth() {
        // 检查设备上是否支持蓝牙
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }


        // 为了确保设备上蓝牙能使用, 如果当前蓝牙设备没启用,弹出对话框向用户要求授予权限来启用
        if (!mBluetoothAdapter.isEnabled()) {
            if (!mBluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
        }

    }

三、搜索BLE设备:

通过调用BluetoothAdapter的startLeScan()搜索BLE设备。调用此方法时需要传入 BluetoothAdapter.LeScanCallback参数。因此你需要实现 BluetoothAdapter.LeScanCallback接口,BLE设备的搜索结果将通过这个callback返回。

由于搜索需要尽量减少功耗,因此在实际使用时需要注意:

1、当找到对应的设备后,立即停止扫描;
2、不要循环搜索设备,为每次搜索设置适合的时间限制。避免设备不在可用范围的时候持续不停扫描,消耗电量。

  /**
     * 扫描设备
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void scanLeDevice(final boolean enable) {
        if (enable) {
            //设置10s的扫描时间,然后停止扫描
            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();
    }

如果你只需要搜索指定UUID的外设,你可以调用 startLeScan(UUID[], BluetoothAdapter.LeScanCallback)方法。
其中UUID数组指定你的应用程序所支持的GATT Services的UUID。

BluetoothAdapter.LeScanCallback的实现如下:

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() {
           //这里参数中的device就是我们搜索到的设备
           //注意我们这里回调是搜索到一个ble设备,就走一次回调,同一个设备可以回调无数次,所以注意添加到集合里面,以免程序崩了
               mLeDeviceListAdapter.addDevice(device);
               mLeDeviceListAdapter.notifyDataSetChanged();
           }
       });
   }
};

注意:搜索时,你只能搜索传统蓝牙设备或者BLE设备,两者完全独立,不可同时被搜索。

好了我们的打开蓝牙到搜索设备就到这里了,就是这么的简单。
在这里我简单的说下连接GATT Server。

四、连接GATT Server

两个设备通过BLE通信,首先需要建立GATT连接。我这里讲的是Android设备作为client端,连接GATT Server。
连接GATT Server,你需要调用BluetoothDevice的connectGatt()方法。

BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
//获得bluetoothdevice

调用BluetoothDevice的connectGatt()方法,此函数带三个参数:Context、autoConnect(boolean)和BluetoothGattCallback对象。调用示例:

mBluetoothGatt = device.connectGatt(this, false, mGattCallback);

如果函数成功,返回BluetoothGatt对象,它是GATT profile的封装。通过这个对象,我们就能进行GATT Client端的相关操作。BluetoothGattCallback用于传递一些连接状态及结果。
BluetoothGattCallback是一个抽象类,他里面有十个方法,每个方法都有一个与连接上的ble设备交互的功能
例如:上面的connectGatt连接成功或失败以后会回调到BluetoothGattCallback中的如下方法:

 @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            String intentAction;
            if (newState == BluetoothProfile.STATE_CONNECTED) {//newState值为2
                intentAction = ACTION_GATT_CONNECTED;
                Log.i(TAG, "连接到GATT服务器.");


            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {//newState值为0
                intentAction = ACTION_GATT_DISCONNECTED;
                 Log.i(TAG, "从GATT 服务器断开连接.");

            }
        }

BluetoothGatt常规用到的几个操作示例:

connect() :连接远程设备。
discoverServices() : 搜索连接设备所支持的service。
disconnect():断开与远程设备的GATT连接。
close():关闭GATT Client端。
readCharacteristic(characteristic) :读取指定的characteristic。
setCharacteristicNotification(characteristic, enabled) :设置当指定characteristic值变化时,发出通知。
getServices() :获取远程设备所支持的services。

等等。

注:
1、某些函数调用之间存在先后关系。例如首先需要connect上才能discoverServices。
2、 一些函数调用是异步的,需要得到的值不会立即返回,而会在BluetoothGattCallback的回调函数中返回。例如 discoverServices与onServicesDiscovered回调,readCharacteristic与 onCharacteristicRead回调,setCharacteristicNotification与 onCharacteristicChanged回调等。

好了这里我们这次就说到这里,具体的连接gatt的详解看我另外一篇博客

http://blog.csdn.net/z957250254/article/details/52411556

光看不行哦!需要自己去实践才能更深入的理解!!!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值