Android -- Service的開啟關閉與生命週期

來源:互聯網
上載者:User

標籤:android   des   style   blog   http   java   

Service是Android 系統中的四大組件之一,是在一段不定的時間運行在後台,不和使用者互動應用組件。

service可以在很多場合的應用中使用,比如播放多媒體的時候使用者啟動了其他Activity這個時候程式要在後台繼續播放,比如檢測SD卡上檔案的變化等等。

生命週期                                                                                 

context.startService() 啟動流程:

context.startService()  -> onCreate()  -> onStart()  -> Service running  -> context.stopService()  -> onDestroy()  -> Service stop 

如果Service還沒有運行,則android先調用onCreate(),然後調用onStart();

如果Service已經運行,則只調用onStart(),所以一個Service的onStart方法可能會重複調用多次。 

如果stopService的時候會直接onDestroy,如果是調用者自己直接退出而沒有調用stopService的話,Service會一直在後台運行,該Service的調用者再啟動起來後可以通過stopService關閉Service。

所以調用startService的生命週期為:onCreate --> onStart (可多次調用) --> onDestroy

context.bindService()啟動流程:

context.bindService()  -> onCreate()  -> onBind()  -> Service running  -> onUnbind()  -> onDestroy()  -> Service stop

onBind()將返回給用戶端一個IBind介面執行個體,IBind允許用戶端回調服務的方法,比如得到Service的執行個體、運行狀態或其他動作。這個時候把調用者(Context,例如Activity)會和Service綁定在一起,Context退出了,Srevice就會調用onUnbind->onDestroy相應退出。 

所以調用bindService的生命週期為:onCreate --> onBind(只一次,不可多次綁定) --> onUnbind --> onDestory。

在Service每一次的開啟關閉過程中,只有onStart可被多次調用(通過多次startService調用),其他onCreate,onBind,onUnbind,onDestory在一個生命週期中只能被調用一次。

開啟關閉                                                                                   

Service的啟動有兩種方式:context.startService() context.bindService()

Service的關閉有兩種方式:context.stopService() context.unbindService()

工程                                                                                          

<service android:name=".PhoneStatusService"></service>

Service的內容:

package com.yydcdut.servicestudy1;import java.io.IOException;import android.app.Service;import android.content.Intent;import android.media.MediaRecorder;import android.os.IBinder;import android.telephony.PhoneStateListener;import android.telephony.TelephonyManager;public class PhoneStatusService extends Service {    @Override    public IBinder onBind(Intent intent) {        return null;    }    @Override    public void onCreate() {        System.out.println("onCreate");        super.onCreate();    }    @Override    public void onStart(Intent intent, int startId) {        System.out.println("onStart");        //監聽電話狀態的變化        TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);        tm.listen(new MyPhoneStatusListener(), PhoneStateListener.LISTEN_CALL_STATE);        super.onStart(intent, startId);    }        @Override    public int onStartCommand(Intent intent, int flags, int startId) {        System.out.println("onStartCommand");        return super.onStartCommand(intent, flags, startId);    }    @Override    public void onDestroy() {        System.out.println("onDestroy");        super.onDestroy();    }}class MyPhoneStatusListener extends PhoneStateListener{    private MediaRecorder recorder;    @Override    public void onCallStateChanged(int state, String incomingNumber) {        switch (state) {        case TelephonyManager.CALL_STATE_IDLE://空閑            if(recorder != null)            {                recorder.stop();                recorder.reset();recorder.release();                recorder = null;            }            break;        case TelephonyManager.CALL_STATE_RINGING://響鈴            System.out.println("發現來電!!!!!");            if("5556".equals(incomingNumber))            {                System.out.println("掛斷電話......");            }            recorder = new MediaRecorder();            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);            recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);            recorder.setOutputFile("/data/data/com.yydcdut.servicestudy1/"+System.currentTimeMillis()+".3gp");            try {                recorder.prepare();            } catch (IllegalStateException e) {                // TODO 自動產生的 catch 塊                e.printStackTrace();            } catch (IOException e) {                // TODO 自動產生的 catch 塊                e.printStackTrace();            }            break;        case TelephonyManager.CALL_STATE_OFFHOOK://通話狀態            if(recorder != null)                recorder.start();            break;        default:            break;        }                super.onCallStateChanged(state, incomingNumber);    }    }

主介面兩個Button開啟和關閉Service:

public void click(View view)    {        Intent intent = new Intent(getApplicationContext(),PhoneStatusService.class);        startService(intent);    }        public void click2(View view)    {        Intent intent = new Intent(getApplicationContext(),PhoneStatusService.class);        stopService(intent);    }

關於生命週期的:

我是天王蓋地虎的分割線                                                               

原始碼:http://pan.baidu.com/s/1dD1Qx01

service學習1.zip

 

 

 

轉載請註明出處:http://www.cnblogs.com/yydcdut

聯繫我們

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