why should i use android service instead of java thread

后端 未结 7 2132
遥遥无期
遥遥无期 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:37

    As per Android Developer Guide (http://developer.android.com/guide/components/services.html#Basics) :

    A service is simply a component that can run in the background even when the user is not interacting with your application. Thus, you should create a service only if that is what you need.

    If you need to perform work outside your main thread, but only while the user is interacting with your application, then you should probably instead create a new thread and not a service. For example, if you want to play some music, but only while your activity is running, you might create a thread in onCreate(), start running it in onStart(), then stop it in onStop(). Also consider using AsyncTask or HandlerThread, instead of the traditional Thread class. See the Processes and Threading document for more information about threads.

    Remember that if you do use a service, it still runs in your application's main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations.

提交回复
热议问题