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

标签 android android-intent android-service

我正在寻找一种无需类(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/

相关文章:

android - 如何避免重复 PendingIntents

android - 为什么 TileService 会等待几秒钟才能启动 Activity?

android - 打盹模式如何影响后台/前台服务,有/没有部分/全部唤醒锁?

java - 停止Android Service创建的线程

javascript - Cordova 媒体插件,如何测试浏览器播放的声音?我总是得到 ReferenceError : Media is not defined

java - 每个滚动条上的项目都会调用 PagerAdapter 实例化项目

android - 应用更新后 SharedPreferences 丢失

android - 在 Google Maps API 中设置标记图标

android - 如何启动 Genius Scan 意向

android - 如何正确使用Intent