A started service is one that another component starts by calling
startService()
, which results in a call to the service's
onStartCommand()
method.
翻譯:其他元件 調用 startService--->service調用 onStartCommand
When a service is started, it has a lifecycle that's independent of the component that started it. The service can run in the background indefinitely, even if the component that started it is destroyed. As such, the service should stop itself when its job is complete by calling
stopSelf()
, or another component can stop it by calling
stopService()
.
翻譯:service一旦start起來了,就和start他的那個元件沒關系了。(啟動它的那個元件關了也沒關系)
是以,service要通過調用stopSelf或者其他元件調用stopService 來終結
An application component such as an activity can start the service by calling
startService()
and passing an
Intent
that specifies the service and includes any data for the service to use. The service receives this
Intent
in the
onStartCommand()
method.
翻譯:應用元件能通過intent給service傳遞資料,service在onStartCommand中接收資料
For instance, suppose an activity needs to save some data to an online database. The activity can start a companion service and deliver it the data to save by passing an intent to
startService()
. The service receives the intent in
onStartCommand()
, connects to the Internet, and performs the database transaction. When the transaction is complete, the service stops itself and is destroyed.
例如:加入一個activity想存點資料到線上資料庫,就可以balabala這樣做,做完後stop itself就好
Caution: A service runs in the same process as the application in which it is declared and in the main thread of that application by default. If your service performs intensive or blocking operations while the user interacts with an activity from the same application, the service slows down activity performance. To avoid impacting application performance, start a new thread inside the service.
service預設在啟動它的那個線程,這個說了好多次了。。。。。
Traditionally, there are two classes you can extend to create a started service:
有兩個類 可以用來 started servcie
Service
This is the base class for all services. When you extend this class, it's important to create a new thread in which the service can complete all of its work; the service uses your application's main thread by default, which can slow the performance of any activity that your application is running.
翻譯:這個記得要自己起線程
IntentService
This is a subclass of
Service
that uses a worker thread to handle all of the start requests, one at a time. This is the best option if you don't require that your service handle multiple requests simultaneously. Implement
onHandleIntent()
, which receives the intent for each start request so that you can complete the background work.
翻譯:如果不需要同時處理多個請求的話,用這個類就行。
實作onHandleIntent方法,這個方法會接收intent
The following sections describe how you can implement your service using either one for these classes.
翻譯:下面描述怎麼用這兩個類