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

Android 四大組件之 Service:生命週期、兩種啟動方式與通訊

編輯:關於 Android 程式設計

Service 是 Android 四大組件之一,性質近似於 Windows 中的服務:通常沒有使用者操作介面,默默運行於系統中不易被察覺。手機裡的程式更新、服務推送,背後多半都有 Service 在支撐。

Service 與 Activity 有幾分相似:都需要在 AndroidManifest.xml 中配置,生命週期也有點像。差別在於 Service 不在前台運行,而是默默在後台工作。

一、Service 的生命週期

Service 與 Activity 一樣存在於當前行程的主線程中,因此阻塞 UI 的耗時操作不能放在 Service 裡直接執行。像是下載這類工作,必須另外開啟子線程處理;如果在 Service 中進行高 CPU 佔用或長時間操作,應用就會跳出「強制關閉還是等待」的對話框。可見 Service 與 Activity 是平級的,四大組件的地位並非浪得虛名。

Service 的生命週期分成兩條路徑:一條是 startService() 啟動後的 onCreate → onStartCommand → onDestroy;另一條是 bindService() 綁定後的 onCreate → onBind → onUnbind → onDestroy。兩條路徑都會經過 onCreate 與 onDestroy,中間環節則依啟動方式而不同。

二、自定義 Service

public class BookService extends Service {
    private String tag = "BookService";

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(tag, "onCreate 啟動了");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(tag, "onStartCommand 啟動了");
        Toast.makeText(this, "BookService 開始了", Toast.LENGTH_SHORT).show();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.i(tag, "onDestroy 銷毀了");
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(tag, "onBind 綁定了");
        return null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(tag, "onUnbind 解綁了");
        return super.onUnbind(intent);
    }
}

記得在 AndroidManifest.xml 中註冊:

<service android:name="com.example.googleservice.BookService"></service>

三、第一種啟動方式:startService / stopService

// 啟動
Intent service = new Intent(this, BookService.class);
startService(service);

// 停止
Intent stopservice = new Intent(this, BookService.class);
stopService(stopservice);

對照 log 輸出,就能清楚看出第一條生命週期路徑的執行順序。

四、第二種啟動方式:bindService / unbindService

先定義一個繼承自 ServiceConnection 的類:

class BookServiceConnection implements ServiceConnection {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
    }
}
// 綁定
Intent binderStartIntent = new Intent(this, BookService.class);
connection = new BookServiceConnection();
bindService(binderStartIntent, connection, Context.BIND_AUTO_CREATE);

// 解綁
unbindService(connection);

五、Activity 與 Service 的通訊

實務上常需要 Activity 直接呼叫 Service 的方法,這時可在 BookService 中定義一個內部 Binder 類,把 Service 實例暴露出去:

class BookBinder extends Binder {
    public BookService getCurrentService() {
        return BookService.this;
    }
}

然後在 Activity 的 onServiceConnected 中取得該實例:

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
    // 取得 Service 實例
    BookService bookService = ((BookService.BookBinder) service).getCurrentService();
    // 接下來就能直接呼叫 Service 對外開放的業務方法
}

六、用 Notification 把後台狀態送到前台

Service 長期在後台工作,可以透過 Notification 把訊息呈現到前台。修改 onCreate():

@Override
public void onCreate() {
    super.onCreate();
    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("QQ空間")
            .setContentText("有新動態,快來看看");
    mNotificationManager.notify(0, mBuilder.build());
    Log.i(tag, "onCreate 啟動了");
}

這樣使用者即使不在應用介面內,也能從通知列得知 Service 的工作狀態。若是長時間运行的任務(如下載、播放),進一步可改用前台服務(foreground service)搭配常駐通知,避免被系統回收。

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