Service 起動前の確認

android.app.Service を起動する前に実行中か確認してから起動したい。

ActivityManager で、実行中の service のリストを取得すれば良いだろう。

以下のようにすれば良い。

ActivityManager manager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);

List<RunningServiceInfo> runningService = manager.getRunningServices(Integer.MAX_VALUE);

for(RunningServiceInfo info : runningService){

   if (info.service.getClassName().equals(SampleService.class.getName())){
      Toast.makeText(context, "サービスは起動済みです"
                    ,Toast.LENGTH_SHORT).show();

      return;  // ここで処理中断
   }
}

startService(new Intent(context, SampleService.class));