我正在寻找一种无需类(class)即可启动 Android 服务的方法。 我发现了很多这样的例子:
startService(new Intent(this, TheService.class));
我不想将服务类放入其中并在我手动停止之前让服务继续运行。
我不需要服务的接口(interface),因为它只应该打开一些没有任何参数的套接字。
服务运行时间不应依赖于应用程序的运行时间: 第一个需要该服务的应用程序应该启动它,然后它应该运行直到它被手动停止。
所以我不能使用 BroadcastReceiver
因为它们生命周期很短。
绑定(bind)到服务将导致取消绑定(bind),从而停止服务(我不想要)。
有没有办法在没有服务的 .class 的情况下使用启动服务? 选择: 有没有一种方法可以绑定(bind)到不将生命周期链接到已启动应用程序的服务?
最佳答案
您可以按名称启动它。像这样:
public static void startYourService(Context context) {
Intent i = new Intent("com.whatever.servicename.YOUR_ACTION_NAME");
i.setPackage(context.getPackageName());
context.startService(i);
}
您需要使用该服务向 apk 添加一个 intent 过滤器:
<service
android:name="com.whatever.servicename"
android:exported="true">
<intent-filter>
<action android:name="com.whatever.servicename.YOUR_ACTION_NAME" />
</intent-filter>
</service>
关于android - 在没有 .class 的情况下启动 Android 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14931006/