Android蓝牙4.0BLE设备通信方法

最新在项目中接触到蓝牙BLE设备,参考了一下官方文档,使用官方API可以使用4.0协议很简单的和设备进行通信,下面就把经验分享一下,本人主要涉及蓝牙功能开启,设备搜索,两个设备之间的通信,首先想使用蓝牙4.0协议调试设备必须是Android4.3以上,由于智能电视本身蓝牙功能就是开启的,所以本文省略掉开启蓝牙的介绍,大家有兴趣可以看一下官方API。首先是访问蓝牙需要的权限mantifest注册如下:

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

使用GATT协议核心类官方文档介绍如下:

Get the BluetoothAdapter

The BluetoothAdapter is required for any and all Bluetooth activity. The BluetoothAdapter represents the device's own Bluetooth adapter (the Bluetooth radio). There's one Bluetooth adapter for the entire system, and your application can interact with it using this object. The snippet below shows how to get the adapter. Note that this approach uses getSystemService() to return an instance of BluetoothManager, which is then used to get the adapter. Android 4.3 (API Level 18) introduces BluetoothManager:

private BluetoothAdapter mBluetoothAdapter;
...
// Initializes Bluetooth adapter.
final BluetoothManager bluetoothManager =
        (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();

查找BLE设备


我们要注意的就是用户选择连接设备后马上断开连接,并且为搜索动作增加超时,不要一直对设备进行搜索

/**
 * Activity for scanning and displaying available BLE devices.
 */
public class DeviceScanActivity extends ListActivity {
  

    private BluetoothAdapter mBluetoothAdapter;
    private boolean mScanning;
    private Handler mHandler;

    // Stops scanning after 10 seconds.
    private static final long SCAN_PERIOD = 10000;
    ...
    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);
                }
            }, SCAN_PERIOD);

            mScanning = true;
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
  
            mScanning = false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
        ...
    }
...
}

If you want to scan for only specific types of peripherals, you can instead call startLeScan(UUID[], BluetoothAdapter.LeScanCallback), providing an array of

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值