android - 停止 Activity 中的服务

标签 android service android-intentservice

我正在使用以下代码来停止我的服务

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

这是我的无限期服务

public class UsageRecorderService extends IntentService {

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

  @Override
  protected void onHandleIntent(Intent intent) {

      while (true) {

          UsageRecorder.recordUsages(this, false);

          SystemClock.sleep(10000);
      }
   }
}

为什么不停止我的服务?

最佳答案

这段代码可以工作

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);

我还建议阅读Services guide了解那里发生了什么。

关于android - 停止 Activity 中的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27459885/

相关文章:

java - Android 在应用程序完全关闭之前向服务器发出请求

android - 使用 OkHttp 检查套接字是否连接或断开连接的更好方法?

android - 从服务通知 Activity

Android:如何确定 IntentService 是否正在运行?

android - 从 IntentService 使用 ContentProvider

Android 服务和线程中运行的重复性任务

php - 连接mysql数据库的php问题

java - 如何避免类型转换?

android - 在 Android 中声明维度、颜色、资源 ID 或其他非标准数据类型的数组?

android - 当我的服务运行 TimerTask 时,如何防止 UI 挂起?