Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
86 views
in Technique[技术] by (71.8m points)

foregroundService in android java


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you are using androidx (which IMO you should be), you can use ContextCompat.startForegroundServce which works on all API versions

If not, you can check the API version before you call:

if (Build.VERSION.SDK_INT >= 26) {
    context.startForegroundService(intent);
} else {
    context.startService(intent);
}

Note that Service.startForeground is available since API 5, which means your service can be foreground without calling startForegroundService on those API versions.

If you are curious why that changed in API 26, here is a quote from the documentation:

Prior to Android 8.0, the usual way to create a foreground service was to create a background service, then promote that service to the foreground. With Android 8.0, there is a complication; the system doesn't allow a background app to create a background service. For this reason, Android 8.0 introduces the new method?startForegroundService()?to start a new service in the foreground. After the system has created the service, the app has five seconds to call the service's?startForeground()?method to show the new service's user-visible notification. If the app does?not?call?startForeground()?within the time limit, the system stops the service and declares the app to be?ANR.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...