1.在AndroidManifest文件中添加需要的权限
android:name="android.permission.BLUETOOTH" /> android:name="android.permission.BLUETOOTH_ADMIN" /> android:name="android.permission.ACCESS_COARSE_LOCATION" /> 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);
(2)读取设备返回的数据//写入数据的回调 @Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { super.onCharacteristicWrite(gatt, characteristic, status); }
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