Android BLE Bluetooth uses one
Posted by bladecatcher on Mon, 30 Mar 2020 23:01:32 +0200
Android ble Bluetooth development
I. whether BLE Bluetooth is supported
private boolean isSupportBluetooth(boolean istoast) {
if (!this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
if (istoast) {
Toast.makeText(this, "Your device does not support Bluetooth", Toast.LENGTH_SHORT).show();
}
return false;
}
final BluetoothManager bluetoothManager =
(BluetoothManager) this.getSystemService(Context.BLUETOOTH_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
mBluetoothAdapter = bluetoothManager.getAdapter();
}
if (mBluetoothAdapter == null) {
if (istoast) {
Toast.makeText(this, "Your device does not support Ble Bluetooth", Toast.LENGTH_SHORT).show();
}
return false;
}
return true;
}
Second, if it is supported, we register the broadcast receiver to receive the Bluetooth data we need, and then the specific Bluetooth operation is encapsulated in the mybluetooth service to bind the service. Finally, if you want to determine whether Bluetooth is enabled, if you want to enable Bluetooth scanning, we need to apply for permission before scanning. Here, we use the EasyPermissions framework to request permission. Finally, we need to enable scanning
/**
* Initializing Bluetooth device includes opening Bluetooth and other operations
*/
private void initBluetooth() {
supportBluetooth = isSupportBluetooth(true);
if (supportBluetooth) {
registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
Intent gattServiceIntent = new Intent(this, MyBluetoothLeService.class);
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
if (mBluetoothAdapter.isEnabled()) {
if (EasyPermissions.hasPermissions(this, bluePermission)) {
startBluetoothSearch();
} else {
EasyPermissions.requestPermissions(this, "", Constant.REQUESTBLUETOOTHKEY, bluePermission);
}
} else {
initRequestOpenBluetooth();
}
}
}
/**
* Request to turn on Bluetooth device
*/
private void initRequestOpenBluetooth() {
Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(mIntent, Constant.REQUESTTOOPENBLUE);
}
/**
* To enable Bluetooth scanning, you need to stop Bluetooth scanning by delaying
*/
private void startBluetoothSearch() {
mBluetoothAdapter.startLeScan(this);
handler.sendEmptyMessageDelayed(0, delayMillis);
}
Today, I'd like to share whether BLE Bluetooth is supported, whether Bluetooth is enabled, and whether Bluetooth scanning is enabled. In this case, we recommend using the methods noted above for the previous version of Bluetooth scanning. Don't forget the application and declaration of permission BL Bluetooth needs to locate permission.
Topics:
Android