我正在编写一个应用程序,该程序通过广播接收器侦听蓝牙事件ACL_CONNECTED
和ACL_DISCONNECTED
,并启动一些使用服务的工作。但是,我遇到了两个问题:
1)广播接收者并非总是收到这些意图,尤其是当手机的屏幕关闭了一段时间后 2)服务无法从广播接收器可靠地启动
最近在前台打开我的应用程序时,代码工作正常。但是,我等待的时间更长(尤其是当我关闭手机屏幕时)1)和2)不再可靠地发生。
这是我的广播接收者:
public class BluetoothConnectedReceiver extends BroadcastReceiver {
private static final String TAG = "BluetoothReceiver";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "bluetoothreceiver received event");
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Context applicationContext = context.getApplicationContext();
if (device.getBluetoothClass().getMajorDeviceClass() == BluetoothClass.Device.Major.AUDIO_VIDEO) {
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
Log.d(TAG, "Received intent with acl connected");
Intent i = new Intent(context, BluetoothDetectionService.class);
i.setAction(BluetoothDetectionService.ACTION_HEADSET_ON);
applicationContext.startService(i);
} else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
Log.d(TAG, "Received intent with acl disconnected");
Intent i = new Intent(context, BluetoothDetectionService.class);
i.setAction(BluetoothDetectionService.ACTION_HEADSET_OFF);
applicationContext.startService(i);
}
}
}
}
在我的服务中,我在onStartCommand
中有一份打印声明。
有时,我仅从广播接收器接收打印声明,例如“已连接acl的接收到的意图”,但没有从服务接收打印声明。其他时候,我什至没有从广播接收器获得打印声明。