1
0

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.

Serviceとtimerを止める

Last updated at Posted at 2019-12-16

定期的にスクリーンショットを取得するサービスが中々終了しなかったので記載。
タイマー処理付きのサービスはタイマー停止後にサービスを止める
(サービスだけ止めてもタイマーは裏で動き続け、プロセスが残る)。
ここではServiceで定義したtask(timer)をcancelし、stopServiceで止めている。

サービスの起動確認をする場合、タイマーを止めなければtrueが通り続ける。

サービス名:SService

Activity.java
        //タイマー処理確認
        SService ssservice= new SService();
        if(ssservice.task != null) {
            ssservice.task.cancel();
            ssservice.task = null;
        }

        //サービス停止
        android.content.Intent _intent;
        _intent = new android.content.Intent(getApplicationContext(), ssservice.class);
        getApplicationContext().stopService(_intent);

以下のソースでサービスの起動確認が可能。参考にどうぞ

Activity.java
private boolean isMyServiceRunning(Class<?> serviceClass) {
        //サービス起動確認
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                //サービス起動済み
                return true;
            }
        }
        //サービスが起動していない
        return false;
}
1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?