繁体   English   中英

如何在广播接收器中调用服务方法?

[英]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

现在,如果您正在寻找一种维护蓝牙连接,发现设备,发送和接收数据的服务...如果是这种情况,那么根据我的经验,我会提出以下几点意见:

希望它可以帮助干杯

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM