在活动停止服务 [英] Stop service in an activity

查看:147
本文介绍了在活动停止服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用下面的code停止我的服务

I'm using following code to stop my service

Intent intent = new Intent(MainActivity.this, UsageRecorderService.class);
stopService(intent);

这是我的服务,它的工作原理无限期

And this is my service that works indefinitely

public class UsageRecorderService extends IntentService {

  public UsageRecorderService() {
      super("UsageRecorder");
  }

  @Override
  protected void onHandleIntent(Intent intent) {

      while (true) {

          UsageRecorder.recordUsages(this, false);

          SystemClock.sleep(10000);
      }
   }
}

为什么不停止我的服务?

Why does not stop my service?

推荐答案

这code将工作

public class UsageRecorderService extends IntentService {

    private boolean mStop = false;

    public UsageRecorderService() {
        super("UsageRecorder");
    }

    public final Object sLock = new Object();

    public void onDestroy() {
        synchronized (sLock) {
            mStop = true;
        }
    }


    @Override
    protected void onHandleIntent(Intent intent) {
        while (true) {
            synchronized (sLock) {
                if (mStop) break;
            }
            UsageRecorder.recordUsages(this, false);
            SystemClock.sleep(10000);
        }
    }

}

您可以使用 stopService

Intent intent = new Intent(MainActivity.this, UsageRecorderService.class);
stopService(intent);

此外,我建议阅读服务指南明白是怎么回事那里。

Also I recommend to read Services guide to understand what is going there.

这篇关于在活动停止服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆