Androidプログラマへの道 〜 Moonlight 明日香 〜 - サービスの状態をチェックする
サービスが実行中かチェックするには, ActivityManagerクラスを利用する.

サービスの状態チェック

インテントでサービスを起動/停止する」を参照して, サービスの起動/停止ができるようにする.
  • src/ServiceActivity.java
    • getSystemServiceメソッドで, ActivityManagerのインスタンスを取得する.
    • ActivityManager#getRunningServicesメソッドで, 起動中のサービス情報(RunningServiceInfo)を取得する.
    • RunningServiceInfo.service#getClassNameメソッドで, 実行中のサービスのクラス名を取得し, 確認したいサービスのクラス名と比較する. 一致するものがあればサービス起動中.
package com.moonlight_aska.android.service01;

import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class ServiceActivity extends Activity implements View.OnClickListener {
  private Button btnStart = null;
  private Button btnStatus = null;
  private Intent intent = null;
  private boolean mode = false;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_service);

    btnStart = (Button)findViewById(R.id.service_btn);
    btnStart.setOnClickListener(this);
    btnStatus = (Button)findViewById(R.id.status_btn);
    btnStatus.setOnClickListener(this);
    // サービスクラスを指定
    intent = new Intent(this, TestService.class);
  }

  @Override
  public void onClick(View v) {
    // TODO Auto-generated method stub
    int viewId = v.getId();
    if (viewId == R.id.service_btn) {
      if (!mode) {
        // サービスの起動
        startService(intent);
        btnStart.setText(R.string.stop_label);
        mode = true;
      }
      else {
        // サービスの停止
        stopService(intent);
        btnStart.setText(R.string.start_label);
        mode = false;
      }
    }
    else if (viewId == R.id.status_btn) {
      // サービスが実行中かチェック
      ActivityManager am = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
      List<RunningServiceInfo> listServiceInfo = am.getRunningServices(Integer.MAX_VALUE);
      boolean found = false;
      for (RunningServiceInfo curr : listServiceInfo) {
        // クラス名を比較
        if (curr.service.getClassName().equals(TestService.class.getName())) {
          // 実行中のサービスと一致
          Toast.makeText(this, "サービス実行中", Toast.LENGTH_LONG).show();
          found = true;
          break;
        }
      }
      if (found == false) {
        Toast.makeText(this, "サービス停止中", Toast.LENGTH_LONG).show();
      }
    }
  }
}