两个蓝牙设备配对时如何捕捉

时间:2016-11-13 19:27:26

标签: java android bluetooth

有没有办法抓住两个蓝牙设备配对的时刻?

实际上我有一个带有两个ListView的应用程序 - 一个配对设备,另一个配新设备。每次用户从“新发现的设备”列表中选择设备时,都会出现一个警告对话框,询问他是否要与此设备配对。单击“是”后,将执行pairDevice函数,并且必须更新两个列表,以便我们配对的设备从列表中删除"新发现的设备"并被添加到列表"配对设备"。

我可以创建两个列表,编写发现功能,为列表添加onClickevent"新发现的设备"并为其编写pairDevice函数,但每次我启动我的应用程序并单击“新发现的设备”列表中的项目时,程序会显示一条消息"不幸的是,您的应用程序已停止"但是在下面我还有另一个对话窗口,询问我是否要与所选设备配对(这里是screenshot),这意味着应用程序仍在运行。

这是我的代码的一部分,我尝试配对设备和更新列表:

    // New Devices List
    mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,arrListNew);
    newListView = (ListView) findViewById(R.id.new_lv);
    titleNewListView = (TextView)findViewById(R.id.title_new_lv);
    // New Devices List View item click
    newListView.setClickable(true);
    // Newly discovered devices OnClick Event
    newListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
        @Override
        public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
            final String info = ((TextView) view).getText().toString();
            int address = info.indexOf(":");
            final String adr = info.substring(address-2,info.length());

            // Pair two devices method
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setMessage("Pair with a chosen device?");
            builder.setPositiveButton("yes", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(adr);

                    pairDevice(device);

                    // update list with Paired Devices
                    arrListPaired.add(device);
                    mPairedDevicesArrayAdapter.notifyDataSetChanged();

                    // update list with Newly Discovered Devices
                    arrListNew.remove(device);
                    mNewDevicesArrayAdapter.notifyDataSetChanged();
                }
            });
            builder.setNegativeButton("No", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.cancel();
                }
            });
            AlertDialog alertDialog = builder.create();
            alertDialog.show();
        }
    });

我的pairDevice功能:

private void pairDevice(BluetoothDevice device) {
    try {
        Method method = device.getClass().getMethod("createBond", (Class[]) null);
        method.invoke(device, (Object[]) null);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

提前感谢任何建议!

0 个答案:

没有答案