所以我正在编写一个使用蓝牙发现设备的Android应用程序。这是我用来开始发现的代码。
try {
myBluetoothAdapter.startDiscovery();
Log.d("Bluetooth Started successfully","yes");
} catch (Error e) {
Log.d("FAILED","Ya failed mate");
e.printStackTrace();
}
然后我注册一个BroadcastReceiver来监视何时找到设备。这是我的代码
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
final ArrayList<String> stringArrayList = new ArrayList<>();
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_list_item_1,stringArrayList);
final ListView listView = findViewById(R.id.listView);
listView.setAdapter(arrayAdapter);
BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d("ACTION RECEIVED","Action was received");
Log.d("Device Name", String.valueOf(intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)));
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
stringArrayList.add(device.getName());
arrayAdapter.notifyDataSetChanged();
listView.invalidateViews();
}
}
};
registerReceiver(myReceiver,intentFilter);
listView,arrayAdapter和stringArrayList就是我“登录”的东西。
问题是每当我运行该代码时,我都会收到此错误并且我的代码无法运行。我假设它不起作用的原因是因为这个错误。
W/BroadcastQueue: Background execution not allowed: receiving Intent { act=android.bluetooth.adapter.action.DISCOVERY_STARTED flg=0x10 } to com.verizon.messaging.vzmsgs/com.verizon.vzmsgs.receiver.DevicePairingListener
有人能告诉我这个错误意味着什么,以及如何解决它?
我还发现Stack Overflow上的其他问题,其错误看起来非常相似;比如,它将在BOOT_COMPLETED,ACTION_POWER_DISCONECTED或BATTERY_LOW的上下文中,而不是蓝牙。那些与此类似的是怎样的。
我认为这是因为Android O的隐式广播禁令,要解决这个问题,你可以使你的targetSDKVersion小于26。你可以在这里找到更多https://commonsware.com/blog/2017/04/11/android-o-implicit-broadcast-ban.html
在我的情况下 - Android 9(API级别28)我必须在代码中定义我的BroadcastReceiver
才能使它工作。
像这样(在我的情况下在服务中添加 - 无关紧要)
private MyReceiver myReceiver;
@Override
public void onCreate() {
myReceiver = new MyReceiver();
this.registerReceiver(myReceiver, new IntentFilter("android.intent.action.myreceiver"));
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(myReceiver);
}
private class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
try {
if (intent.getAction().equals("android.intent.action.myreceiver")) {
//logic goes here
}
} catch (Exception e) {
//some log goes here
}
}
}
像这样发送广播
Intent intentMy = new Intent();
intentMy.setAction("android.intent.action.myreceiver");
intentMy.putExtra("whatever", true);
sendBroadcast(intentMy);