咱们本部分文章主要探讨低功耗蓝牙的开发,关于经典蓝牙的开发不是本系列文章的探讨范围。android
咱们都知道对于Android设备而言,是在Android 4.3(API 18)以后开始支持低功耗蓝牙。不清楚Android设备中蓝牙的发展过程的,能够阅读Android设备中的蓝牙这篇文章。也就是说本系列文章主要就是基于Android 4.3以后的开发经验。bash
咱们上面已经提到因为低版本的Android设备会存在不支持低功耗蓝牙的状况,因此咱们须要首先检测是否存在低功耗蓝牙模块:ui
/**
* Check wheather support Bluetooth LE.
* <p>是否支持低功耗蓝牙</p>
*
* @param context
* @return
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public static boolean checkBluetoothLEAvaiblelability(@NonNull Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
return BluetoothAdapter.getDefaultAdapter() != null;
} else {
return false;
}
}复制代码
/**
* Return true if Bluetooth is currently enabled and ready for use.
* <p>蓝牙是否打开</p>
*
* @return true if the local adapter is turned on
*/
@RequiresPermission(Manifest.permission.BLUETOOTH)
public static boolean isEnableBluetooth() {
final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter != null) {
return adapter.isEnabled();
} else {
return false;
}
}复制代码
方法一:使用Intent打开蓝牙spa
/**
* Turn on the local Bluetooth adapter—do not use without explicit
* ser action to turn on Bluetooth.
* <p>
* onActivityResult() method will be called when action finished
* </p>
*
* @param activity activity
* @param requestCode requestCode
*/
@RequiresPermission(Manifest.permission.BLUETOOTH)
public static void enableBLuetooth(Activity activity, int requestCode) {
final Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
activity.startActivityForResult(intent, requestCode);
}复制代码
优势:有回调。
.net
缺点:使用不太方便。code
注意:打开蓝牙须要“Manifest.permission.BLUETOOTH”权限。blog
方法二:使用BluetoothAdapterci
BluetoothAdapter.getDefaultAdapter().enable();复制代码
开启低功耗蓝牙须要检查是否支持支持低功耗蓝牙,同时须要在注册清单添加以下代码 :开发
<uses-feature
android:name="android.hardware.bluetooth_le"
android:required="true" />
<!--蓝牙相关-->
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />复制代码