8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Android】サービスが実行中かチェックしてから起動する

Last updated at Posted at 2017-11-13

無駄にサービスのインスタンスを増やしたくなかったので、実行中かチェックしてから起動する。
minSdkVersion 23
targetSdkVersion 23
で確認しました。

HogeService.java
import android.app.ActivityManager;
...

ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo serviceInfo : manager.getRunningServices(Integer.MAX_VALUE)) {
    if (HogeService.class.getName().equals(serviceInfo.service.getClassName())) {
    	// 実行中なら起動しない
        return;
    }
}
Intent intent = new Intent(getApplication(), HogeService.class);
startService(intent);
8
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?