[英]Can't call a Bluetooth BroadcastReceiver method in a Service
[英]How to call a service method in a broadcastreceiver?
因此,我有一个启动服务的应用程序。 此服务开始使用BTAdapter.startDiscovery()扫描蓝牙设备。 另外,我有一个广播接收器,它监听DISCOVERY_FINISHED动作。 如果发生这种情况,我想从服务中的onReceive()中调用一个方法,以再次启动扫描过程。 我该怎么办?
这是我的接收者:
public class PollingReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ScanBTService sBTs = new ScanBTService();
sBTs.startScan();
}
}
这里的服务:
public class ScanBTService extends IntentService {
private BluetoothAdapter mBTAdapter;
private PollingReceiver mPollingReceiver;
public ScanBTService() {
super("ScanBTService");
}
@Override
protected void onHandleIntent(Intent intent) {
final BluetoothManager btManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBTAdapter = btManager.getAdapter();
mBTAdapter.startDiscovery();
}
public void startScan() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mBTAdapter.startDiscovery();
}
}
在onReceive()方法中,使用以下两行重新启动服务。 我没有对其进行测试,但是它应该可以那样工作。
@Override
public void onReceive(Context context, Intent intent) {
//ScanBTService sBTs = new ScanBTService();
//sBTs.startScan();
Intent i = new Intent(getApplicationContext(), ScanBTService.class);
startService(i);
}
然后,您也可以删除startScan()方法。
尝试使用以下方法解决该方法:
context.startService(new Intent(context, SimpleWakefulService.class));
由于使用的是IntentService,因此需要为启动的服务创建一个Intent来处理。
这可以通过以下方法实现:
Intent intent = new Intent(context, ScanBTService.class);
startService(intent);
如此处所述: https : //developer.android.com/training/run-background-service/send-request.html
现在,如果您正在寻找一种维护蓝牙连接,发现设备,发送和接收数据的服务...如果是这种情况,那么根据我的经验,我会提出以下几点意见:
解决此问题的最佳方法(当然,这取决于您在做什么)可能是在单独的进程中运行服务,该进程负责所有这些。 检查: http : //developer.android.com/guide/topics/manifest/service-element.html和标记
android:process
利用Android的IPC通信功能在您的主应用线程和服务之间传递和接收消息。 教程: http : //www.survivingwithandroid.com/2014/01/android-bound-service-ipc-with-messenger.html 。
创建和维护连接快速指南: http : //developer.android.com/guide/topics/connectivity/bluetooth.html#ConnectingAsAClient
希望它可以帮助干杯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.