Monday, December 13, 2010

何謂Service

Service文件裡提到︰
A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.
Service是應用程式的其中一種元件,它意謂著當一隻APK在不需要與使用者互動時還要運作,因而存在。

Each service class must have a corresponding <service> declaration in its package's AndroidManifest.xml. Services can be started with Context.startService() and Context.bindService().
Service在使用時,必須在AndroidManifest.xml裡宣告

使用Service的方式有2:
1.Context.startService()
A facility for the application to tell the system about something it wants to be doing in the background.
Service是一個讓應用程式告訴系統想在背景做些什麼事的工具。
2.Context.bindService()
A facility for an application to expose some of its functionality to other applications.
Service是一個讓應用程式展示它內部函式功能給其它應用程式的媒介。


Note that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work.
Service就像其它應用程式的物件一樣,在該程序Process的主執行緒運作著。
所以,當我們要用到像高度的CPU運算(像是播放MP3)或是一些會卡住的運算(像網路運算),那麼就應該建立出一個自己的執行緒,好讓工作能順利完成。

The IntentService class is available as a standard implementation of Service that has its own thread where it schedules its work to be done.
IntentService是一個標準實作Service的類別,它呢,擁有一個獨立的執行緒,靠這個類別,就能完成上述所提到的「獨立完成作業」。


Processes and Threads一文中提到︰

 When the first of an application's components needs to be run, Android starts a Linux process for it with a single thread of execution.



By default, all components of the application run in that process and thread.
However, you can arrange for components to run
in other processes
, and you can spawn additional threads for any process.

當應用程式的元件(指Activity、Service、BroadcastReceiver和ContentProvider)要啟動的時候,Android會去開啟Linux裡進程的單一執行緒,開始做運算處理。
預設來說,應用程式中的所有元件,都會在"那個"進程和執行緒運作。
所以,如果要制定元件在某個特定進程運作時,程式設計師可以自行決定要在哪個另外的進程或新增的執行緒下去執行應用程式。

參考網站
1.書生雜記
2.程式搖滾

No comments:

Post a Comment