正如问题标题所问,我想知道它们之间的区别是什么,因为文档不是很清楚它们是否真的存在差异。
提前致谢。
最佳答案
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);
}
}
关于java - ContextCompat.startForegroundService(context, intent) 和 startforegroundservice(intent) 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51938000/