基本上我在这里尝试两件事,我试图在我的蓝牙设备连接到特定设备时开始烤面包(因此需要检查这是否是特定的蓝牙名称),如果那是特定的设备那么我想显示一个烤面包当连接到该特定的蓝牙设备时。当我的蓝牙与该特定的蓝牙设备断开连接时,我也想举杯祝酒。这是我的代码: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();
}
}
}
在我的代码中,接收器正确地调用了Toast,即使断开连接的Toast也可以正常工作,但已连接的Toast永远无法正常工作。
请让我知道为什么CONNECTED Toast不起作用,以及当连接到特定设备时如何使此代码起作用(我不想为所有设备显示此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)) {
}
}
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句