Application threads vs Service threads

后端 未结 3 1411
余生分开走
余生分开走 2020-12-01 10:30

What are the advantages/disadvantages in placing a lengthy network access code in a thread in an activity or a thread in a service? How would it affect the application? I

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 10:56

    The difference is how the system manages your application process lifecycle. Running threads don't affect the application process lifecycle, but a service does.

    To determine which processes should be killed when low on memory, Android places each process into an importance hierarchy based on the components running in them and the state of those components. If your app doesn't have a visible activity or a foreground service but has a background service, it's categorized as a service process and will be kept alive while there less priority cached processes exist. But if the app has neither a visible activity/fragment, foreground service nor a background service, it's categorized as a cached process and can be killed at any time to free system resources, whether it has a running thread or not.

    But do not rush to create a background service, there are more modern approaches to deal with background tasks nowadays. Consider alternative solutions described below and in the background processing guide and keep in mind all restrictions associated with background services.

    If a thread executes a task which result is required only by an activity, the thread lifecycle should be bound to the activity. In such a case no services are required. It's so called immediate tasks, ViewModel + Kotlin Coroutines + ViewModelScope is a great way to deal with it, see Guide to background processing for more details about different kinds of background tasks.

    If the task should be completed whether the user closed you app or not and it's not required to execute it immediately, consider using WorkManager which is a great way to deal with such deferred tasks. See Android Work Manager vs Services? for more details.

    Otherwise, if you have an immediate task which lifecycle isn't bound to an activity/fragment, may be a foreground service would be the best choice, especially in case of an audio player. There are some limitations considering background services since Android 8, the system stops an app's background services in several minutes after the app is closed, so it's not a place for a long running task.

提交回复
热议问题