Android Service生命週期及用法

來源:互聯網
上載者:User

上一節我講解了Android Activity的生命週期,這一節我將講解一下Service,首先我們要知道Service具體是幹什麼的,什麼時候用到?以及它的生命週期等。

Service概念及用途:

Android中的服務,它與Activity不同,它是不能與使用者互動的,不能自己啟動的,運行在背景程式,如果我們退出應用時,Service進程並沒有結束,它仍然在後台運行,那我們什麼時候會用到Service呢?比如我們播放音樂的時候,有可能想邊聽音樂邊幹些其他事情,當我們退出播放音樂的應用,如果不用Service,我們就聽不到歌了,所以這時候就得用到Service了,又比如當我們一個應用的資料是通過網路擷取的,不同時間(一段時間)的資料是不同的這時候我們可以用Service在後台定時更新,而不用每開啟應用的時候在去擷取。

Service生命週期 :

Android Service的生命週期並不像Activity那麼複雜,它只繼承了onCreate(),onStart(),onDestroy()三個方法,當我們第一次啟動Service時,先後調用了onCreate(),onStart()這兩個方法,當停止Service時,則執行onDestroy()方法,這裡需要注意的是,如果Service已經啟動了,當我們再次啟動Service時,不會在執行onCreate()方法,而是直接執行onStart()方法,具體的可以看下面的執行個體。

Service與Activity通訊:

Service後端的資料最終還是要呈現在前端Activity之上的,因為啟動Service時,系統會重新開啟一個新的進程,這就涉及到不同處理序間通訊的問題了(AIDL)這一節我不作過多描述,當我們想擷取啟動的Service執行個體時,我們可以用到bindService和onBindService方法,它們分別執行了Service中IBinder()和onUnbind()方法。

為了讓大家 更容易理解,我寫了一個簡單的Demo,大家可以模仿著我,一步一步的來。

第一步:建立一個Android工程,我這裡命名為ServiceDemo.

第二步:修改main.xml代碼,我這裡增加了四個按鈕,代碼如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    > <TextView  android:id="@+id/text"       android:layout_width="fill_parent"      android:layout_height="wrap_content"      android:text="@string/hello"     /> <Button  android:id="@+id/startservice"  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:text="startService" /> <Button  android:id="@+id/stopservice"  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:text="stopService" /> <Button  android:id="@+id/bindservice"  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:text="bindService" /> <Button  android:id="@+id/unbindservice"  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:text="unbindService" /></LinearLayout>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.