关于Android连接蓝牙的方法

来源:互联网 发布:实时汇率软件 编辑:程序博客网 时间:2024/06/01 08:43

尊重原创,转载请注明出处 我是原文

今天在看自己的项目时,看到了关于蓝牙连接的这部分,在此做个笔记。在之前,蓝牙连接的方法为:

BluetoothDevice.createBond();

不过我记得那时所用的 API 版本这个方法是隐藏的 @hide ,具体是哪个版本的 API 我也不记得了,

然后今天无意间看了下源码,发现:

    /**     * Start the bonding (pairing) process with the remote device.     * <p>This is an asynchronous call, it will return immediately. Register     * for {@link #ACTION_BOND_STATE_CHANGED} intents to be notified when     * the bonding process completes, and its result.     * <p>Android system services will handle the necessary user interactions     * to confirm and complete the bonding process.     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.     *     * @return false on immediate error, true if bonding will begin     */    public boolean createBond() {        if (sService == null) {            Log.e(TAG, "BT not enabled. Cannot create bond to Remote Device");            return false;        }        try {            return sService.createBond(this);        } catch (RemoteException e) {Log.e(TAG, "", e);}        return false;    }

是的,这个方法是公开的了。

当我直接将代码改为直接使用后

deviceItem.createBond();

发现了这样的提示

意思是说这个方法是在API版本为19后(Android 4.4)才开始可以使用的。

所以建议在Android版本为4.4以下的手机上,这么使用:

                        try {                                Method bondDevice = BluetoothDevice.class                                        .getMethod("createBond");                                bondDevice.invoke(deviceItem);                            } catch (NoSuchMethodException e) {                                e.printStackTrace();                            } catch (IllegalAccessException e) {                                e.printStackTrace();                            } catch (IllegalArgumentException e) {                                e.printStackTrace();                            } catch (InvocationTargetException e) {                                e.printStackTrace();                            }

整理过后,可以变为:

                        if(android.os.Build.VERSION.SDK_INT<19){                                try {                                    Method bondDevice = BluetoothDevice.class                                            .getMethod("createBond");                                    bondDevice.invoke(deviceItem);                                } catch (NoSuchMethodException e) {                                    e.printStackTrace();                                } catch (IllegalAccessException e) {                                    e.printStackTrace();                                } catch (IllegalArgumentException e) {                                    e.printStackTrace();                                } catch (InvocationTargetException e) {                                    e.printStackTrace();                                }                            } else {                                deviceItem.createBond();                            }

注:deviceItem 为 BluetoothDevice 对象。

0 0