Android 蓝牙 BLE蓝牙 浅析

BluetoothAdapter,获取方式有两种:

①BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

②BluetoothManager manager = (BluetoothMange) context.getSystemService(Context.BLUETOOTH_SERVICE);
if(manager != null) { 
    /*最低的编译版本是api18*/
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    BluetoothAdapter mAdapter = manager.getAdapter();   
}

打开蓝牙有三种方式:

①adapter.enable; // 系统会询问是否打开蓝牙
②Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivitForResult(intent, RCODE); // 打开蓝牙,RCODE,请求Tag
③Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(intent); 
// 系统询问打开蓝牙300s能够被别的设备扫描到

数据传递使用socket.getOutputStream()/socket.getInputStream();
调用read的方法是会阻塞线程的,所以要放异步线程中去做。而调用write()的方法是要是另一端没有及时调用write()方法的话,也会阻塞线程的。
蓝牙连接一般要在Service中,防止用户界面给干掉,在Service中的Threadn run()中一般是写一个死循环持续读/写取流数据。
并且在Service中定义一个cancel()方法,用于用户取消蓝牙连接。之后再调用停止线程回收资源。
*注意,当两台设备互相连接的时候。要先将一台开启为服务器,而另一条调用connect()才会成功。

低功耗蓝牙(API18以上)
Bluetooth Low Energy (BLE)

// 用于检测应用是否支持低功耗蓝牙
// 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();
}

有句话需要注意:
Note: You can only scan for Bluetooth LE devices or scan for Classic Bluetooth devices, as described in Bluetooth. You cannot scan for both Bluetooth LE and classic devices at the same time.
查找设备分查找传统蓝牙设备和低功耗蓝牙设备。不能够同一时间查找两种设备。而且要是搜索的设备不支持低功耗的话,那么是搜索不到的哦。

①打开蓝牙->②查找设备,startLeScan(…)->③连接设备device.connectGatt(…)->④通过控制BluetoothGatt来传递数据。

蓝牙传输数据要一段时间。所以一般是定义一个绑定了的Service。在Service中绑定BluetoothGattCallBack接口,而在操作Gatt进行数据传输的时候,BluetoothGattCallBack中的回调就会触发。从而用于用户UI展示,和数据传递。通过Characteristic来获取一些传递和获取一些特性。

而Gatt.setCharacteristicNotification(…)是设置BluetoothGattCallback#onCharacteristicChanged回调是否触发的。

https://developer.android.com/guide/topics/connectivity/bluetooth.html?hl=zh-cn#Profiles
低功耗蓝牙4.0
https://developer.android.com/guide/topics/connectivity/bluetooth-le.html?hl=zh-cn#setup

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值