蓝牙自动配对 4.2.2

这几天一直都在研究Android手机上蓝牙的自动配对与连接。

整理一下思路,整体的流程是:

1. 首先注册蓝牙的广播消息

    /**
     * 蓝牙的隐藏action,主要是配对时弹出配对对话框时会响应该消息
     */
    protected static final String sPairingName = "android.bluetooth.device.action.PAIRING_REQUEST";

    public void register(Context context) {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);                // 发现蓝牙设备
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);   // 蓝牙设备配对状态发生改变,详细可查看官方文档
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);   // 蓝牙开始扫描
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);  // 蓝牙扫描结束
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);       // 蓝牙状态改变,即开启或者关闭,多种状态
        filter.addAction(sPairingName);         
        context.registerReceiver(this, filter);
    }

2. 如何配对蓝牙

在发现蓝牙设备后,可以获取到BluetoothDevice的对象

if (action.equals(BluetoothDevice.ACTION_FOUND)) {
            BluetoothDevice device = intent
                    .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
}

这里就可以进行配对操作。。不过官方将创建配对的API给隐藏了起来。下面我门来看看与自动配对相关的几个函数,来自BluetoothDevice

    /**
     * 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
     * @hide   // 该函数是对外公开的,但是在这里加上hide之后,IDE中无法直接调用需要通过反射来调用
     */
    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;
    }

通过反射来调用createBond,下面的代码是反射“createBond”方法,createBond会激发蓝牙事件 BluetoothDevice.ACTION_BOND_STATE_CHANGED与 

"android.bluetooth.device.action.PAIRING_REQUEST",在4.2.2版本的Android上这里会弹出配对对话框。

    public void bond() {
        Method createBondMethod;
        try {
            createBondMethod = mDevice.getClass().getMethod("createBond");
            createBondMethod.invoke(mDevice);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

在"android.bluetooth.device.action.PAIRING_REQUEST"事件下,反射调用setPin方法,设置PIN码,然后在调用一次createBond就会将配对对话框隐藏掉。

会有一点点延迟,这里需要继续跟进,看能否不让其弹出。

 

posted @ 2013-04-20 12:21  染煞之心  阅读(1635)  评论(1编辑  收藏  举报