从 activity 调用服务方法而不绑定

Call service methods from activity without binding

我有一个推送服务 运行ning 用于我的应用程序,负责保持 TCP 连接活动并在传入消息上创建通知。

即使 activity 已关闭,我也需要此服务到 运行,因此网上发布的解决方案是调用 startService() 而不是 bind(),确实如此解决服务结束于 activity destroyed.

的问题

但是,如果没有 Binder,我该如何调用服务的方法?我设法开始工作的一种方式是通过 BroadcastReceiver。有没有更简单的方法来实现这种行为?

添加一个您用来调用 startService 的操作,每个不同的 method/case 您想要 call/handle,并使用 intent.getAction() 检索它,当 [=12] =]被称为

来自 startService

的文档

Every call to this method will result in a corresponding call to the target service's onStartCommand(Intent, int, int) method, with the intent given here. This provides a convenient way to submit jobs to a service without having to bind and call on to its interface.