gpt4 book ai didi

java - BroadcastReceiver 在连接蓝牙时通知

转载 作者:行者123 更新时间:2023-11-29 08:58:34 25 4
gpt4 key购买 nike

我想制作一个 BroadcastReceiver,当蓝牙连接到另一台设备时通知我。

BroadcastReceiver bluetooth = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() == android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED) {
Toast.makeText(MainActivity.this, "done!", Toast.LENGTH_LONG)
.show();
}
}
};

    IntentFilter ff = new IntentFilter();
ff.addAction(android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED);
registerReceiver(bluetooth, ff);

和AndroidManifest.xml

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

但是当设备连接时,没有任何反应,为什么?

最佳答案

试试这个方法:

getApplicationContext().registerReceiver(receiver,
new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));

getApplicationContext().registerReceiver(receiver,
new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));

private final BroadcastReceiver mReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action))
{
// LOG - Connected
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action))
{
// LOG - Disconnected
}
}
}

希望对你有帮助。

关于java - BroadcastReceiver 在连接蓝牙时通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18892971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com