基本上我在这里尝试2件事,我试图在我的蓝牙设备连接到特定设备时开始敬酒(因此需要检查这是否是特定的蓝牙名称),如果那是特定设备那么我想要显示祝酒词连接到特定的蓝牙设备时。当我的蓝牙与特定的蓝牙设备断开连接时,我也想表示祝酒。这是我的代码:在manifest.xml中
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<receiver android:name=".MyBluetoothReceiver" >
<intent-filter>
<action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED" />
</intent-filter>
</receiver>
班级代码:
public class MyBluetoothReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "RECEIVER CALLED!!", Toast.LENGTH_LONG).show();
if(intent.getAction().equals(
"android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED")){
// code for Bluetooth connect
Toast.makeText(context, "CONNECTED!!", Toast.LENGTH_LONG).show();
}
if(intent.getAction().equals(
"android.bluetooth.device.action.ACL_DISCONNECTED")){
//code for Bluetooth disconnect;
Toast.makeText(getApplicationContext(),"DISCONNECTED",Toast.LENGTH_LONG).show();
}
}
}
在我的代码中,我正确地将接收器称为吐司,甚至断开连接的吐司也在工作,但连接的吐司永远无法正常工作。
请让我知道为什么CONNECTED toast不起作用以及如何在连接到特定设备时使此代码工作(我不想为所有设备显示此吐司)。
将您的广播接收器更改为:
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//you can get name by device.getName()
} else if (BluetoothAdapter.ACL_DISCONNECTED
.equals(action)) {
}
}
};