Android 服务和 Intent 过滤器

Android services and Intent filters

当我们在清单中声明类似的东西时,是否保证服务会在收到该类型的意图时执行(如果尚未 运行)?这在 Android Oreo 8.0 上的工作方式是否相同?

    <service
        android:name=".MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>

这取决于您使用的服务类型。

1。 Foreground-: 前台服务执行一些用户能注意到的操作

2: 后台:- 后台服务执行用户不会直接注意到的操作。例如,如果应用程序使用服务来压缩其存储空间,则通常是后台服务。

Note: If your app targets API level 26 or higher, the system imposes restrictions on running background services when the app itself is not in the foreground. In most cases like this, your app should use a scheduled job instead.

3。 绑定 当应用程序组件通过调用 bindService() 绑定到服务时,服务即被绑定。

因此,正如您在 android Oreo 或更高版本的备注中看到的那样,后台服务存在某些限制。有关主题的更多信息,您可以阅读 Here.

is it guaranteed that the service will be executed (if it is not already running) on receiving an intent of that type?

"Guaranteed" 是一个强项。 一般来说你的说法是正确的。不包含的场景:

  • 如果有人尝试使用隐式 Intent 启动服务,一个只有那个操作字符串。很可能一个设备将有多个服务 <intent-filter>,在这种情况下 Android 将只选择其中一个服务来启动。请注意,绑定 使用隐式 Intent 在 Android 5.0+ 上被禁止,以避免这种情况。

  • 如果您在运行时使用 PackageManagersetComponentEnabledSetting() 禁用了该组件。

Does this work the same way on Android Oreo 8.0?

我不知道 Android 8.0 中 <intent-filter><service> 上的行为有任何变化。在 Android 8.0 中对 services 进行了更改(例如,无法从后台启动服务),但这些更改不依赖于 <intent-filter> .