1. 程式人生 > >Android Service 淺析

Android Service 淺析

這篇部落格用如下的結構來講解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 and the diagram on the right shows the lifecycle when the service is created with .

圖左邊顯示的是用startService建立的Service的生命週期,圖右邊顯示的是bindService建立的Service的生命週期。

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小菜鳥,如有錯誤,請您包涵指正。