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

11
作为问题标题所问,我想知道它们的区别是什么,因为文件不太清楚它们是否真的有区别。
谢谢。
1个回答

18

ContextCompat是用于兼容性的实用程序类。

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);
        }
    }

1
谢谢您的回应。我想知道是否在调用前台服务时使用ContextCompat.startForegroundService(this, new Intent(context, myservice.class))与startForegroundService(new Intent(Context, myservice.class))之间有区别。从API 27源代码来看,第一种方式是调用startforeground服务的正确方式? - YSY
是的,您希望在使用最新的API建议时保持兼容性。 - Tuby

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接