Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Service 生命週期與使用方式完整解說

編輯:關於 Android 程式設計

Service 是 Android 四大元件之一,適合執行不需要使用者互動、且必須在背景持續運作的任務。本文先釐清它的生命週期,再透過一個可直接運行的範例把啟動與綁定兩種用法講明白。

Service 的生命週期(適用 2.1 以上)

  1. 被 startService 啟動:無論是否有任何 Activity 綁定,它都會在背景運行。流程為 onCreate()(若需要)→ onStart()。多次呼叫 startService 會觸發多次 onStart,但不會建立多個 Service 實例,只需一次 stop。它會持續運行,直到被 stopService、呼叫自身 stopSelf(),或系統資源不足時被回收。
  2. 被 bindService 綁定:呼叫 bindService 建立連線後,服務便持續運行。若只綁定而未 startService,則只會執行 onCreate(),不會呼叫 onStart;此時一旦解除綁定,系統即可回收該 Service(連線銷毀導致解除,解除後便銷毀)。
  3. 既啟動又綁定:類似 startService 的週期,onCreate 與 onStart 都會被呼叫。
  4. 停止服務時:呼叫 stopService 會顯式觸發 onDestroy();若沒有啟動、只是不再有綁定,則會隱式呼叫。值得注意的是,在有 bind 的情況下,stopService() 並不會生效。

Activity 端程式碼

以下範例某些細節需搭配 logcat 觀察:

package jtapp.myservicesamples;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class AcMain extends Activity implements OnClickListener {
    private static final String TAG = "AcMain";
    private Button btnStart, btnStop, btnBind, btnExit;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findView();
    }

    private void findView() {
        btnStart = (Button) findViewById(R.id.Start);
        btnStop = (Button) findViewById(R.id.Stop);
        btnBind = (Button) findViewById(R.id.Bind);
        btnExit = (Button) findViewById(R.id.Exit);

        btnStart.setOnClickListener(this);
        btnStop.setOnClickListener(this);
        btnBind.setOnClickListener(this);
        btnExit.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent("jtapp.myservicesamples.myservice");
        switch (v.getId()) {
            case R.id.Start:
                startService(intent);
                Toast.makeText(this,
                    "myservice running " + MyService.msec / 1000.0 + "s.",
                    Toast.LENGTH_LONG).show();
                break;
            case R.id.Stop:
                stopService(intent);
                Toast.makeText(this,
                    "myservice running " + MyService.msec / 1000.0 + "s.",
                    Toast.LENGTH_LONG).show();
                break;
            case R.id.Bind:
                bindService(intent, sc, Context.BIND_AUTO_CREATE);
                break;
            case R.id.Exit:
                this.finish();
                break;
        }
    }

    private MyService serviceBinder;

    private ServiceConnection sc = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "in onServiceDisconnected");
            serviceBinder = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "in onServiceConnected");
            serviceBinder = ((MyService.MyBinder) service).getService();
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}

版面配置 main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="@string/hello" />
    <Button android:text="Start MyService" android:id="@+id/Start"
        android:layout_width="wrap_content" android:layout_height="wrap_content"/>
    <Button android:text="Stop MyService" android:id="@+id/Stop"
        android:layout_width="wrap_content" android:layout_height="wrap_content"/>
    <Button android:text="Bind MyService" android:id="@+id/Bind"
        android:layout_width="wrap_content" android:layout_height="wrap_content"/>
    <Button android:text="Exit AcMain" android:id="@+id/Exit"
        android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</LinearLayout>

MyService.java

package jtapp.myservicesamples;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {
    private static final String TAG = "MyService";
    public static long msec = 0;
    private boolean bThreadRunning = true;

    private final IBinder binder = new MyBinder();

    public class MyBinder extends Binder {
        MyService getService() {
            return MyService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (bThreadRunning) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                    }
                    Log.i(TAG, "myservice running " + (msec += 100) + "ms.");
                }
            }
        }).start();
    }

    @Override
    public void onDestroy() {
        bThreadRunning = false;
        super.onDestroy();
    }
}

別忘了在 AndroidManifest.xml 註冊

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="jtapp.myservicesamples" android:versionCode="1"
    android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name"
        android:debuggable="true">
        <activity android:name=".AcMain" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="MyService">
            <intent-filter>
                <action android:name="jtapp.myservicesamples.myservice"></action>
            </intent-filter>
        </service>
    </application>
</manifest>

把這三部分接起來,你就能透過四顆按鈕分別測試 startService、stopService 與 bindService,並在 logcat 觀察 Service 的實際生命週期。理解「啟動」與「綁定」的差異,是掌握 Service 的關鍵。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved