why should i use android service instead of java thread

后端 未结 7 2136
遥遥无期
遥遥无期 2021-02-02 12:56

I am confused with android services and java thread.

Please help me to understand in which scenario i should use them.

As per my understanding

7条回答
  •  花落未央
    2021-02-02 13:32

    Services are more analogous to a headless Activity.

    The the important piece to understand is that a Service is about managing application lifetime and the ability to keep work running when your Application is not in the foreground (no UI visible). It is also about providing the ability to expose functionality to other apps.

    http://developer.android.com/reference/android/app/Service.html#WhatIsAService

    Typically when starting a Service you will also start a worker Thread. There are settings in the manifest that can cause a Service to be started in a new Process but generally you do not need to do this, it makes communication with your service more difficult.

    Use a just Thread in your Activity when you need to offload work from the UI thread while the application is in the foreground, but this work can stop when you are no longer in the foreground. (It is possible that your app will continue to run when not it foreground but there is no guarantee depending on a number of factors) Generally speaking Android is free to kill your Activity if it is not in the foreground, and if your App process has no Activities or Services it can be killed.

    Use a Service with a Thread to do work that will take place while your app is in the background and you want better guarantee about the lifetime.

    Use a Service to expose non-UI functionality to other applications.

提交回复
热议问题