安卓學習之服務基本用法

來源:互聯網
上載者:User

標籤:

 服務的生命週期

  服務被啟動後,會回調onStartCommand()方法, 如果這個服務是第一次建立,那麼會調用onCreate()方法。服務啟動之後會一直運行直到stopService()或stopSelf()方法被調用。雖然每調用一次 startService()方法,

但是服務只會存在一個執行個體。所以不管調用幾次startService()方法,只需調用一次 stopService()或 stopSelf()方法,服務就會停止下來了。

  調用 Context的bindService()方法,可以擷取服務的串連,這時候就會調用服務的onBind()方法,返回IBinder對象的執行個體, 這樣就能和服務進行通訊了。只要和服務的串連沒有斷開,服務就會一直保持運行狀態。

  所以當調用startService()方法後,又去調用stopService()方法,這時服務中的onDestroy()方法就會執行,表示服務銷毀。當調用了 bindService()方法後,又去調用unbindService()方法,onDestroy()方法也會執行。如果一個活動被調用了startService()和bindService()方法,那麼我們就要同時調用stopService()和unbindService()方法,這樣onDestory()方法才會被執行。

  這些就遍曆了服務的生命週期。

 

服務

  服務要在AndroidManifest.xml中註冊

  服務的建立:

public class LongRunningService extends Service {    @Override    public IBinder onBind(Intent intent) {        return null;    }    @Override    public void onCreate() {        super.onCreate();    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        return super.onStartCommand(intent, flags, startId);    }    @Override    public void onDestroy() {        super.onDestroy();    }}

 

  onBind()方法是一個抽象類別,所以必須實現它。當服務第一次調用時,就會調用onCreate(),調用onStartCommand()方法。 之後調用服務就不會在調用onCreate()方法,直接調用onStartCommand()方法。onDestory()方法
會在服務銷毀時調用。




 

安卓學習之服務基本用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.