日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

Android中Service(服務(wù))詳解

 quasiceo 2016-03-10
2012-07-21 18:21 79239人閱讀 評(píng)論(15) 收藏 舉報(bào)
分類:

Service是Android中四大組件之一,在Android開發(fā)中起到非常重要的作用,先來(lái)看一下官方對(duì)Service的定義:

Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.


翻譯過(guò)來(lái)就是:Service(服務(wù))是一個(gè)沒有用戶界面的在后臺(tái)運(yùn)行執(zhí)行耗時(shí)操作的應(yīng)用組件。其他應(yīng)用組件能夠啟動(dòng)Service,并且當(dāng)用戶切換到另外的應(yīng)用場(chǎng)景,Service將持續(xù)在后臺(tái)運(yùn)行。另外,一個(gè)組件能夠綁定到一個(gè)service與之交互(IPC機(jī)制),例如,一個(gè)service可能會(huì)處理網(wǎng)絡(luò)操作,播放音樂,操作文件I/O或者與內(nèi)容提供者(content provider)交互,所有這些活動(dòng)都是在后臺(tái)進(jìn)行。

Service有兩種狀態(tài),“啟動(dòng)的”和“綁定”


Started
A service is "started" when an application component (such as an activity) starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. Usually, a started service performs a single operation and does not return a result to the caller. For example, it might download or upload a file over the network. When the operation is done, the service should stop itself.
Bound

A service is "bound" when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.


通過(guò)startService()啟動(dòng)的服務(wù)處于“啟動(dòng)的”狀態(tài),一旦啟動(dòng),service就在后臺(tái)運(yùn)行,即使啟動(dòng)它的應(yīng)用組件已經(jīng)被銷毀了。通常started狀態(tài)的service執(zhí)行單任務(wù)并且不返回任何結(jié)果給啟動(dòng)者。比如當(dāng)下載或上傳一個(gè)文件,當(dāng)這項(xiàng)操作完成時(shí),service應(yīng)該停止它本身。


還有一種“綁定”狀態(tài)的service,通過(guò)調(diào)用bindService()來(lái)啟動(dòng),一個(gè)綁定的service提供一個(gè)允許組件與service交互的接口,可以發(fā)送請(qǐng)求、獲取返回結(jié)果,還可以通過(guò)夸進(jìn)程通信來(lái)交互(IPC)。綁定的service只有當(dāng)應(yīng)用組件綁定后才能運(yùn)行,多個(gè)組件可以綁定一個(gè)service,當(dāng)調(diào)用unbind()方法時(shí),這個(gè)service就會(huì)被銷毀了。

另外,在官方的說(shuō)明文檔中還有一個(gè)警告:


Caution: 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). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.


意思是service與activity一樣都存在與當(dāng)前進(jìn)程的主線程中,所以,一些阻塞UI的操作,比如耗時(shí)操作不能放在service里進(jìn)行,比如另外開啟一個(gè)線程來(lái)處理諸如網(wǎng)絡(luò)請(qǐng)求的耗時(shí)操作。如果在service里進(jìn)行一些耗CPU和耗時(shí)操作,可能會(huì)引發(fā)ANR警告,這時(shí)應(yīng)用會(huì)彈出是強(qiáng)制關(guān)閉還是等待的對(duì)話框。所以,對(duì)service的理解就是和activity平級(jí)的,只不過(guò)是看不見的,在后臺(tái)運(yùn)行的一個(gè)組件,這也是為什么和activity同被說(shuō)為Android的基本組件。

Service生命周期中的一些方法:

                        


通過(guò)這個(gè)圖可以看到,兩種啟動(dòng)service的方式以及他們的生命周期,bind service的不同之處在于當(dāng)綁定的組件銷毀后,對(duì)應(yīng)的service也就被kill了。service的聲明周期相比與activity的簡(jiǎn)單了許多,只要好好理解兩種啟動(dòng)service方式的異同就行。


service生命周期也涉及一些回調(diào)方法,這些方法都不用調(diào)用父類方法,具體如下:

  1. <span style="font-family:Comic Sans MS;font-size:18px;">public class ExampleService extends Service {  
  2.     int mStartMode;       // indicates how to behave if the service is killed  
  3.     IBinder mBinder;      // interface for clients that bind  
  4.     boolean mAllowRebind; // indicates whether onRebind should be used  
  5.   
  6.     @Override  
  7.     public void onCreate() {  
  8.         // The service is being created  
  9.     }  
  10.     @Override  
  11.     public int onStartCommand(Intent intent, int flags, int startId) {  
  12.         // The service is starting, due to a call to startService()  
  13.         return mStartMode;  
  14.     }  
  15.     @Override  
  16.     public IBinder onBind(Intent intent) {  
  17.         // A client is binding to the service with bindService()  
  18.         return mBinder;  
  19.     }  
  20.     @Override  
  21.     public boolean onUnbind(Intent intent) {  
  22.         // All clients have unbound with unbindService()  
  23.         return mAllowRebind;  
  24.     }  
  25.     @Override  
  26.     public void onRebind(Intent intent) {  
  27.         // A client is binding to the service with bindService(),  
  28.         // after onUnbind() has already been called  
  29.     }  
  30.     @Override  
  31.     public void onDestroy() {  
  32.         // The service is no longer used and is being destroyed  
  33.     }  
  34. }</span>  

關(guān)于Service生命周期還有一張比較易懂的圖(來(lái)源于網(wǎng)絡(luò))



另外,這里要說(shuō)明Service的一個(gè)子類,IntentService,首先看下官方文檔的說(shuō)明:

IntentService

This is a subclass of Service that uses a worker thread to handle all start requests, one at a time. This is the best option if you don't require that your service handle multiple requests simultaneously. All you need to do is implement onHandleIntent(), which receives the intent for each start request so you can do the background work.


IntentService使用隊(duì)列的方式將請(qǐng)求的Intent加入隊(duì)列,然后開啟一個(gè)worker thread(線程)來(lái)處理隊(duì)列中的Intent,對(duì)于異步的startService請(qǐng)求,IntentService會(huì)處理完成一個(gè)之后再處理第二個(gè),每一個(gè)請(qǐng)求都會(huì)在一個(gè)單獨(dú)的worker thread中處理,不會(huì)阻塞應(yīng)用程序的主線程,這里就給我們提供了一個(gè)思路,如果有耗時(shí)的操作與其在Service里面開啟新線程還不如使用IntentService來(lái)處理耗時(shí)操作。而在一般的繼承Service里面如果要進(jìn)行耗時(shí)操作就必須另開線程,但是使用IntentService就可以直接在里面進(jìn)行耗時(shí)操作,因?yàn)槟J(rèn)實(shí)現(xiàn)了一個(gè)worker thread。對(duì)于異步的startService請(qǐng)求,IntentService會(huì)處理完成一個(gè)之后再處理第二個(gè)。


看下IntentService的具體實(shí)現(xiàn):

  1. <span style="font-family:Comic Sans MS;font-size:18px;color:#222222;">public class HelloIntentService extends IntentService {  
  2.   
  3.   /**  
  4.    * A constructor is required, and must call the super IntentService(String) 
  5.    * constructor with a name for the worker thread. 
  6.    */  
  7.   public HelloIntentService() {  
  8.       super("HelloIntentService");  
  9.   }  
  10.   
  11.   /** 
  12.    * The IntentService calls this method from the default worker thread with 
  13.    * the intent that started the service. When this method returns, IntentService 
  14.    * stops the service, as appropriate. 
  15.    */  
  16.   @Override  
  17.   protected void onHandleIntent(Intent intent) {  
  18.       // Normally we would do some work here, like download a file.  
  19.       // For our sample, we just sleep for 5 seconds.  
  20.       long endTime = System.currentTimeMillis() + 5*1000;  
  21.       while (System.currentTimeMillis() < endTime) {  
  22.           synchronized (this) {  
  23.               try {  
  24.                   wait(endTime - System.currentTimeMillis());  
  25.               } catch (Exception e) {  
  26.               }  
  27.           }  
  28.       }  
  29.   }  
  30. }</span>  

關(guān)于停止Service,如果service是非綁定的,最終當(dāng)任務(wù)完成時(shí),為了節(jié)省系統(tǒng)資源,一定要停止service,可以通過(guò)stopSelf()來(lái)停止,也可以在其他組件中通過(guò)stopService()來(lái)停止,綁定的service可以通過(guò)onUnBind()來(lái)停止service。

關(guān)于Service還有很多知識(shí),這里就不再一一列舉,可以參考 http://developer./guide/components/services.html


加入我們的QQ群或微信公眾賬號(hào)請(qǐng)查看:Ryan's zone公眾賬號(hào)及QQ群


歡迎關(guān)注我的新浪微博和我交流:@唐韌_Ryan

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多