Android 5.0 BLE 周边(BluetoothLeAdvertiser)

转自 http://blog.csdn.net/songzeyang99/article/details/41727023

      具有低功耗蓝牙模块的设备可以扮演2个角色,中心,周边。周边是数据提供者,中心是数据接收/处理者。IOS设备可以很好的扮演这2个角色,利用现成的API就能开发出具有周边和中心功能的应用,我大Android就有点悲催了,自Android 4.3的系统就规定了BLE的API,但是仅限于中心,至于周边一直没有API的支持。直到2014.6.26 Android Lollipop的面世,才带来了周边API的支持(BluetoothLeAdvertiser)。

这里写图片描述

      利用空闲时间看了看文档写了个一段关于BLE 周边的代码,当我兴冲冲的运行在Nexus5上面时,瞬间就crash了空指针异常,看了下源代码

/**
 * Returns a {@link BluetoothLeAdvertiser} object for Bluetooth LE Advertising operations, or null if Bluetooth LE Advertising is not support on this device.
 * <p>
 * Use {@link #isMultipleAdvertisementSupported()} to check whether LE Advertising is supported on this device before calling this method.
 */
public BluetoothLeAdvertiser getBluetoothLeAdvertiser() {
    if (getState() != STATE_ON) {
        return null;
    }
    if (!isMultipleAdvertisementSupported()) {
        return null;
    }
    synchronized(mLock) {
        if (sBluetoothLeAdvertiser == null) {
            sBluetoothLeAdvertiser = new BluetoothLeAdvertiser(mManagerService);
        }
    }
    return sBluetoothLeAdvertiser;
}

使用方式

final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter mBluetoothAdapter =  bluetoothManager.getAdapter();

BluetoothLeAdvertiser advertiser = mBluetoothAdapter.getBluetoothLeAdvertiser();

AdvertiseData data = new AdvertiseData.Builder().addServiceUuid(ParcelUuid.fromString(ADVERTISER_SERVICE_UUID)).build();

AdvertiseSettings settings = new AdvertiseSettings.Builder().setConnectable(true).build();

advertiser.startAdvertising(settings , data, new AdvertiseCallback() {
    @Override
    public void onStartSuccess(AdvertiseSettings settingsInEffect) {
        super.onStartSuccess(settingsInEffect);
    }
});
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值