ContextCompat.startForegroundService(context, intent) 和 startforegroundservice(intent) 有什么区别?

What is the difference between ContextCompat.startForegroundService(context, intent) and startforegroundservice(intent)?

正如问题标题所问,我想知道它们的区别是什么,因为文档不是很清楚它们是否真的有区别。

提前致谢。

ContextCompat 是出于兼容性目的的实用程序 class。

context.startForegroundService 是在 Android Oreo(API 26) 中引入的,是启动前台服务的新正确方法。在 Android Oreo 之前,您只需调用 startService,这就是 ContextCompat.startForegroundService 所做的。在 API 26 之后调用 context.startForegroundService 否则调用 context.startService

代码来自 ContextCompat API 27 个来源。

/**
     * startForegroundService() was introduced in O, just call startService
     * for before O.
     *
     * @param context Context to start Service from.
     * @param intent The description of the Service to start.
     *
     * @see Context#startForegeroundService()
     * @see Context#startService()
     */
    public static void startForegroundService(Context context, Intent intent) {
        if (Build.VERSION.SDK_INT >= 26) {
            context.startForegroundService(intent);
        } else {
            // Pre-O behavior.
            context.startService(intent);
        }
    }