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

YSY*_*YSY 2 java android foreground-service

正如问题标题所示,我想知道他们的差异是什么,因为如果他们确实存在差异,则文档不是很清楚.

提前致谢.

Tub*_*uby 8

ContextCompat 是出于兼容性目的的优秀级别.

context.startForegroundService是在Android Oreo(API 26)中引入的,是启动前台服务的新方法.在Android Oreo之前你必须打电话startService,那就是做什么ContextCompat.startForegroundService.在API 26之后,它会调用context.startForegroundService或调用context.startService.

从代码ContextCompatAPI 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);
        }
    }
Run Code Online (Sandbox Code Playgroud)