当我正在开发一个应显示可以在我的环境中连接的蓝牙设备的应用程序时,我正在尝试使用BroadcastReceiver列出它们。但是实际上没有列出任何设备,并且onReceive函数也不会触发。
我的清单中也获得了蓝牙的许可...
活动代码
Button button_connect_bluetooth;
LinearLayout linearLayout_bluetooth_devices;
TextView textView_devices[]= new TextView[200];
int index_device =0;
private BluetoothAdapter mBluetoothAdapter;
@SuppressLint("WrongViewCast")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connection);
button_connect_bluetooth =(Button) findViewById(R.id.button_connect_bluetooth);
linearLayout_bluetooth_devices = (LinearLayout) findViewById(R.id.linearLayout_bluetooth_devices);
makeDiscoverable();
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.startDiscovery();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(myReceiver, filter);
}
@Override
protected void onDestroy() {
unregisterReceiver(myReceiver);
super.onDestroy();
}
//Handy für 300 Sekunden sichtbar machen
private void makeDiscoverable() {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
private final BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
//Gefundene Objekte in die Liste hinzufügen
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
textView_devices[index_device]= new TextView(Connection.this);
textView_devices[index_device].setTextColor(Color.parseColor("#00ADEF"));
textView_devices[index_device].setTextSize(12);
textView_devices[index_device].setId(index_device);
textView_devices[index_device].setText(device.getName());
textView_devices[index_device].setPadding(15, 0, 0, 0);
textView_devices[index_device].setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.list_overview_textviews_design, null));
linearLayout_bluetooth_devices.addView(textView_devices[index_device]);
index_device++;
showDeviceFoundToast("Found device " + device.getName());
}
}
};
public void showDeviceFoundToast (String message){
Toast.makeText(Connection.this, message,
Toast.LENGTH_LONG).show();
}
}
Manifest.xml
我正在具有Android 10的三星Galaxy A51上尝试此应用...
如果有人可以帮助我,那将是很好!