android - 如何在广播接收器中使用配对的蓝牙设备数据打开应用程序
问题描述
我的应用程序是使用 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;
}
}
}
从这一点开始我应该怎么做才能得到想要的结果。任何其他方式也欢迎。
解决方案
推荐阅读
- c# - 使用 LINQ 基于单个属性过滤 EntityCollection:
- regex - UltraEdit(或 MacOS 正则表达式):删除 xml 中的多行
- android - 搜索 .droid 和 .yydebug 编辑器的编辑器
- rust - 如何为实现特定特征的所有类型大规模实现反序列化?
- javascript - 错误创建映射{错误:[mapper_parsing_exception]没有在字段[类别]上声明的类型[字符串]的处理程序
- java - 如何使用不同的实现异步调用多个方法
- c# - 如何使用数据注释验证来验证给定数量不大于某个数量?
- xml - 从整数值中查找字母(如 123AB456 - 使用 XSLT 代码过滤这些类型的记录)
- java - 两个线程共享同一个数组java
- python - 使用经过训练的模型来预测标签