在没有.class的情况下启动Android服务

时间:2013-02-18 06:58:34

标签: android android-intent android-service

我正在寻找一种在没有课程的情况下启动Android服务的方法。 我找到了许多例子:

startService(new Intent(this, TheService.class));

我不想把服务类放在其中,并且在我手动停止之前仍然运行服务。

我不需要拥有该服务的接口,因为它只应该打开一些没有任何参数的套接字。

服务运行时间不应取决于应用程序的运行时间: 第一个需要服务的App应该启动它,而不是它应该运行直到它被手动停止。

所以我不能使用BroadcastReceiver因为他们活得很短。 绑定到服务将导致unbind停止服务(我不想要)。

有没有办法在没有服务的.class的情况下使用启动服务? 替代方案: 有没有办法绑定到服务,它没有将生命周期链接到已启动的应用程序?

1 个答案:

答案 0 :(得分:6)

您可以按名称开始。像这样:

public static void startYourService(Context context) {
    Intent i = new Intent("com.whatever.servicename.YOUR_ACTION_NAME");
    i.setPackage(context.getPackageName());
    context.startService(i);
}

您需要使用服务向apk添加意图过滤器:

<service
    android:name="com.whatever.servicename"
    android:exported="true">
    <intent-filter>
        <action android:name="com.whatever.servicename.YOUR_ACTION_NAME" />
    </intent-filter>
</service>