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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章