這篇部落格用如下的結構來講解Service:
1.先看一下Service是什麼。
A Service
is an application component that can perform long-running operations in the background and does not provide a user interface.
Service 是一個能夠在後台執行長時間啟動並執行操作並且不提供使用者介面的應用程式組件。Service是Android的四大組件(其實我更喜歡叫他們“四大金剛”)之一。
2.開始一直認為Service運行在後台其他線程裡面的組件,後來發現錯了。答案就在下面這句話中:
A service runs in the main thread of its hosting process—the service does
not create its own thread and does not run in a separate process (unless you specify otherwise)。
Service 運行在主進程中的主線程(也就是人們經常說的UI線程)裡面,Service 不建立自己的線程,同樣也不運在一個單獨的進程(區別於Service所在的應用程式的進程)(除非你指定)。
3.我特別喜歡洋毛子寫的文章或者文檔,特別嚴謹。先說Service的定義,也就是Service是什麼,然後說Service不是什麼(1.A Service is
not a separate process. Service不是一個單獨的進程。 2.A Service is
not a thread. Service不是一個線程。),這樣正反兩方面就能很好地理解Service的基本概念了。
4.說完Service的基本概念,那就該說什麼時候使用Service。 Service什麼時候使用也沒有明確定義,但是可以根據Service的特性可以推斷出來,比如說可以在後台執行,MP3音樂播放那一塊可以用Service實現,比如說可以長時間地執行某種操作,上傳和下載檔案可以用Service實現,等等。
5.那現在是時候講解Service的生命週期了,有些時候圖片比文字更能說清楚一個問題。Service的生命週期如下:
The service lifecycle. The diagram on the left shows the lifecycle when the service is created with
startService()
and the diagram on the right shows the lifecycle when the service is created with
bindService()
.
圖左邊顯示的是用startService建立的Service的生命週期,圖右邊顯示的是bindService建立的Service的生命週期。
這個圖中還給我們指出Service 的建立有兩種方式 1.startService()
方式。 2.bindService()
方式。
6. Service 的代碼執行個體如下:
6.1 Service如果在App中使用,建立一個類繼承Service類或者Service的子類。
6.2 在manifest檔案中聲明這個Service,例如 <service android:name=".MyService"></service>
6.3.1 startService方式啟動 MyService重寫 onStartCommand()方法,如下:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
用startService(new Intent(this,MyService.class));來啟動Service,用stopService(new Intent(this,MyService.class))來停止Service。
6.3.2 bindService 方式啟動 MyService重寫 onStartCommand()方法。
用bindService();來啟動Service,用unBindService()來停止Service。
本人就是一個Android小菜鳥,如有錯誤,請您包涵指正。