Sunday, December 12, 2010

Service一些手札記錄

以下文章來至於Android guide

it's started by calling Context.startService() and stopped by calling Context.stopService(). It can stop itself by calling Service.stopSelf() or Service.stopSelfResult()
靠Context的method:startService()來啟動,
並靠stopService()關閉
另外,Service也能自行自殺:stopSelf()(果然具有服務精神啊!)


Only one stopService() call is needed to stop the service, no matter how many times startService() was called.
只需要呼叫一次stopService()就能關閉Service了。但是startService()愛叫幾次都行!(服務生真是周到!)

The two modes are not entirely separate. You can bind to a service that was started with startService().
開起服務生後,還能綁架他。
For example, a background music service could be started by calling startService() with an Intent object that identifies the music to play.
當叫服務生播音樂後,
Only later, possibly when the user wants to exercise some control over the player or get information about the current song, would an activity establish a connection to the service by calling bindService().
客人想要看歌曲資訊,也許這時後我們能呼叫綁架服務生。
In cases like this, stopService() will not actually stop the service until the last binding is closed. 
這時候,就算要關閉服務生,也因為被我們綁架了,他也逃不了了,除非我們解繩。

另外,服務生因為不是最重要的,所以生命短暫︰
他只有
void onCreate()  活吧!
void onStart(Intent intent)  做事了!
void onDestroy() 去死吧!
However, onStart() is called only for services started by startService().

當然,如果服務生被綁架了,事情就沒有那麼單純了!
快來看看會發生什麼事!?
 會產生3個Callback
IBinder onBind(Intent intent)
boolean onUnbind(Intent intent)
void onRebind(Intent intent)

The onBind() callback is passed the Intent object that was passed to bindService and onUnbind() is handed the intent that was passed to unbindService().
onBind()函式被拿來傳送Intent(意圖),
If the service permits the binding, onBind() returns the communications channel that clients use to interact with the service.
onBind()會回傳管道上和Service互動的資訊

keep in mind that any service, no matter how it's started, can potentially allow clients to bind to it, so any service may receive onBind() and onUnbind() calls.

因為任何的Service都有可能被綁架,所以你會看到實作Service時,都會有onBind()的出現
不管你是用bindService還是startService,總之,Service都有可能接到onBind()呼叫啦!

No comments: