根据标准 Android 文档,启动服务(即启动服务)的首选方法是使用如下所示的显式意图:
// Using explicit intent:
Intent serviceIntent = new Intent(getApplicationContext(), MyService.class);
// or:
Intent serviceIntent = new Intent(this, MyService.class);
startService(serviceIntent);
您还可以使用隐式意图以及清单中指定的操作字符串来启动/停止服务,如下所示:
// Using implicit intent:
static final String serviceAction = "com.example.my.app.services.MYSERVICE";
Intent serviceIntent = new Intent(serviceAction);
startService(serviceIntent);
// AndroidManifest.xml:
<service android:name="com.example.my.app.services.MyService"
android:exported="false" android:process=":services" >
<intent-filter>
<!-- Start/Stop service -->
<action android:name="com.example.my.app.services.MYSERVICE" />
</intent-filter>
</service>
当该服务仅在本地使用时(不允许第三方应用程序启动或绑定到它),文档表明您不应包含意图过滤器在清单中service标签,你应该设置exported标记为假。
注意:活动和服务在单独的进程中运行(:应用程序和:服务进程)。活动和服务之间的通信是通过实现 AIDL 接口来完成的(这样做是因为只有 AIDL 远程接口允许我在需要同时处理 IPC 的服务中进行多线程处理,不仅在活动之间,而且主要在以下运行的服务之间:服务流程)。
我的问题是:
问题 1:当我在应用程序中使用的活动和服务在两个不同的进程中运行时,我是否需要使用隐式意图而不是显式意图来启动和停止服务?
Q2:当 :application 进程消失(被销毁,不再在内存中)并且 :services 进程在后台运行时,如何从新的 :application 进程再次连接到已经运行的 :services 进程?不知何故,我需要再次获得对 :services 进程的引用,以便我可以停止该进程内正在运行的服务。据我所知,这不能使用 AIDL 来完成。
问题是,当资源耗尽时,Android 可以并且将会轻松地销毁 :application 进程,只要 :services 进程继续运行,这对我来说就很好。
(是的,我知道通过将服务设置为前台服务等来影响流程。我也可以阅读手册;)但这不是我的问题)。
当活动和服务位于单独的进程中并使用 AIDL 时,以及当 :application 进程在被 Android 终止后或当 :services 进程需要再次“查找”时,我找不到与我的问题相关的任何信息或答案。用户再次进入应用程序(在他/她之前离开应用程序之后)。
欢迎任何专家级建议。