Android 6.x上Ble开发记录

1.在AndroidManifest文件中添加需要的权限

<!-- 应用使用蓝牙的权限 -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<!-- 扫描蓝牙设备或者操作蓝牙设置 -->
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<!--6.x以上需添加位置权限 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

2.检查权限

//如果 API level 是大于等于 23(Android 6.0) 时判断是否具有权限
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        //判断是否需要向用户解释为什么需要申请该权限
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_COARSE_LOCATION)) {
            Toast.makeText(this, "Android 6.0开始需要打开位置权限才可以搜索到Ble设备", Toast.LENGTH_SHORT).show();
        }
        //请求权限
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                REQUEST_CODE_ACCESS_COARSE_LOCATION);
    } else {
        //检查蓝牙是否可用 和初始化蓝牙     一般情况下6.0以上均支持ble开发
        checkBleSupportAndInitialize();
        init();
    }
}

private void checkBleSupportAndInitialize() {
    // 检查设备是否支持ble
    if (!getPackageManager().hasSystemFeature(
            PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(this, "不支持蓝牙ble",
                Toast.LENGTH_SHORT).show();
        return;
    }
    // 初始化蓝牙适配
    final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();
    
    if (mBluetoothAdapter == null) {
        // Device does not support Blue tooth
        Toast.makeText(this,
                "没有蓝牙权限", Toast.LENGTH_SHORT)
                .show();
        return;
    }
    //打开蓝牙
    if (!mBluetoothAdapter.isEnabled()) {
        mBluetoothAdapter.enable();
    }

}
3.扫描设备

public void scanDevice() {
    if (isScanning) {
        return;
    }
    mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            if (!isScanning) {
                return;
            }
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
            isScanning = false;
        }
    }, 10000);
    mBluetoothAdapter.startLeScan(mLeScanCallback);
    isScanning = true;
}
BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
    @Override
    public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
        mBluetoothDevice = mBluetoothAdapter
                .getRemoteDevice(device.getAddress());
        // TODO Auto-generated method stub
        String deviceName = device.getName();
        String deviceAddress = device.getAddress();
 
        et_device.setText("名称:" + deviceName + "地址:" + deviceAddress);
           
    }
};
4.连接设备

mBluetoothGatt = mBluetoothDevice.connectGatt(MainActivity.this, false, mGattCallback);
//连接蓝牙的状态回调                                                                              private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, final int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //5.0以上的版本可以设置最大传输字节为512                                         int sdkInt = Build.VERSION.SDK_INT;
                        if (sdkInt >= 21) {
                            //设置最大发包、收包的长度为512个字节
                            if (requestMtu(512)) {
                                Toast.makeText(MainActivity.this, "最大传输字节为512", Toast.LENGTH_SHORT).show();
                            } else
                                Toast.makeText(MainActivity.this, "最大传输字节为20", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MainActivity.this, "最大传输字节为20", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                //如果设备断开,10s后重新连接设备                                                          statu = status;
                handler.postDelayed(mRunnable, 10000);

            }
        }
    };
5.数据通信

连接成功即可进行数据通信,通过硬件组提供的读、写、和通知的UUID,进行相关的通信

(1)向设备写入数据

gattCharacteristic.setValue(str.getBytes());

//将设置好的特征发送出去
mBluetoothGatt.writeCharacteristic(gattCharacteristic);
//写入数据的回调
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    super.onCharacteristicWrite(gatt, characteristic, status);
}

(2)读取设备返回的数据

mBluetoothGatt.readCharacteristic(gattCharacteristic);
//读取数据的回调
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    super.onCharacteristicRead(gatt, characteristic, status);
}
(3)通过notify获取数据

mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
//接收notify数据
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
    super.onCharacteristicChanged(gatt, characteristic);
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            byte[] bytes = characteristic.getValue();
        }
    });

6.断开连接,关闭蓝牙

mBluetoothGatt.disconnect();
mBluetoothAdapter.disable();
最后附上demo链接:http://download.csdn.net/download/shangguanzhangjing/10206178     

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值