蓝牙开发之开启蓝牙

221 阅读2分钟

一、前言

我们本部分文章主要探讨低功耗蓝牙的开发,关于经典蓝牙的开发不是本系列文章的探讨范围。

我们都知道对于Android设备而言,是在Android 4.3(API 18)之后开始支持低功耗蓝牙。不清楚Android设备中蓝牙的发展过程的,可以阅读Android设备中的蓝牙这篇文章。也就是说本系列文章主要就是基于Android 4.3之后的开发经验。

二、蓝牙的开启

我们上面已经提到由于低版本的Android设备会存在不支持低功耗蓝牙的情况,所以我们需要首先检测是否存在低功耗蓝牙模块:

​/**

     * 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打开蓝牙

/**

     * Turn on the local Bluetooth adapter&mdash;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);

    }

优点:有回调。

缺点:使用不太方便。

注意:打开蓝牙需要“Manifest.permission.BLUETOOTH”权限。

方法二:使用BluetoothAdapter

BluetoothAdapter.getDefaultAdapter().enable();
​注意:打开蓝牙需要“Manifest.permission.BLUETOOTH_ADMIN”权限。

三、总结:

开启低功耗蓝牙需要检查是否支持支持低功耗蓝牙,同时需要在注册清单添加如下代码 :

<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" />