首页 > 解决方案 > 如何在广播接收器中使用配对的蓝牙设备数据打开应用程序

问题描述

我的应用程序是使用 obd 扫描仪(提供蓝牙接口)来获取汽车数据。我想在此应用程序中添加一项功能,即每当汽车的 obd(已配对)在移动设备的蓝牙范围内时,应用程序应自行打开。

我实现这一点的想法是在广播接收器中获取配对设备的列表,如果任何配对设备包含子字符串 obd(小或大写),那么应用程序应该自行打开。

我所取得的成就:每当任何包含 obd 子字符串的蓝牙设备与我的手机连接时,我的应用程序都会自行打开。连接过程由我通过设备设置手动完成。

上述结果的广播内代码:

public class BrodcastBlueTooth extends BroadcastReceiver {
    public BrodcastBlueTooth() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        String DeviceName=null;
        String action = intent.getAction();
//        Log.d("BroadcastActions", "Action "+action+"received");
        int state;
        BluetoothDevice bluetoothDevice;

        switch(action)
        {

            case BluetoothDevice.ACTION_ACL_CONNECTED:
                bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Toast.makeText(context, "Connected to "+bluetoothDevice.getName(), Toast.LENGTH_SHORT).show();
                Log.d("BroadcastActions", "Connected to "+bluetoothDevice.getName());

                DeviceName=bluetoothDevice.getName();
                if (DeviceName.contains("OBD")){
                    Intent newIntent = new Intent();
                    newIntent.setClassName("com.quad14.obdnewtry", "com.quad14.obdnewtry.activity.MainActivity");
                    newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    context.startActivity(newIntent);


                }else if(DeviceName.contains("obd")){
                    Intent newIntent = new Intent();
                    newIntent.setClassName("com.quad14.obdnewtry", "com.quad14.obdnewtry.activity.MainActivity");
                    newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    context.startActivity(newIntent);
                }

                break;

            case BluetoothDevice.ACTION_ACL_DISCONNECTED:
                bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//                Toast.makeText(context, "Disconnected from "+bluetoothDevice.getName(),
//                        Toast.LENGTH_SHORT).show();
                break;
        }

我在清单中声明我的广播,所以它总是在后台工作。

我通过以下代码获得了配对设备列表:

   public void PairedDevice(){
            Set<BluetoothDevice> pairedDevices = BTAdapter.getBondedDevices();
            if (pairedDevices.size() > 0) {
                for (BluetoothDevice device : pairedDevices) {
                    PaiedDevices.add(device.getName());

                    Log.e("DeviceName", String.valueOf(PaiedDevices));
                    PairDeviceFlag=true;
                }
            }
        }  

从这一点开始我应该怎么做才能得到想要的结果。任何其他方式也欢迎。

标签: androidbluetooth

解决方案


推荐阅读