1、需要申请如下权限
android:name="android.hardware.bluetooth_le"
android:required="true" />
2、申请运行时权限
/**
* 检查蓝牙权限
*/
public void checkBlePermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
1);
} else {
Log.i("tag","已申请权限");
}
}2.1、重写onRequestPermissionsResult,判断用户是否同意
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1: {
// 如果请求被取消,则结果数组为空。
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i("tag","同意申请");
} else {
Log.i("tag","拒绝申请");
}
return;
}
}
}
3、判断蓝牙是否打开,如果没有打开则打开蓝牙
/**
* 判断是否支持蓝牙,并打开蓝牙
* 获取到BluetoothAdapter之后,还需要判断是否支持蓝牙,以及蓝牙是否打开。
* 如果没打开,需要让用户打开蓝牙:
*/
private void checkBleDevice() {
//首先获取BluetoothManager
BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
//获取BluetoothAdapter
if (bluetoothManager != null) {
BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();
if (mBluetoothAdapter != null) {
if (!mBluetoothAdapter.isEnabled()) {
//调用enable()方法直接打开蓝牙
if (!mBluetoothAdapter.enable()){
Log.i("tag","蓝牙打开失败");
}
else{
Log.i("tag","蓝牙已打开");
}
//该方法也可以打开蓝牙,但是会有一个很丑的弹窗,可以自行尝试一下
// Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
// enableBtIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// startActivity(enableBtIntent);
}
} else {
Log.i("tag","同意申请");
}
}
}
以上三步基本上就能完成Android6.0之后蓝牙的打开了,需要注意一点的是需要API 18以上,如下
minSdkVersion 18
否则在获取adapter的时候会报错!!!!
如果需要兼容到API 18一下,又不会报错,应该怎么做呢,如果哪位大神看到了,留言指导一下,感谢!