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


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);
    }

關於生命周期的截圖:

image

我是天王蓋地虎的分割線                                                               

源代碼:http://pan.baidu.com/s/1dD1Qx01

service學習1.zip

 

 

 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM