2

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

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

为什么不停止我的服务?

4

3 回答 3

2

这段代码可以工作

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

我还建议阅读服务指南以了解那里的情况。

于 2014-12-13T15:27:01.337 回答
0

活动:

sendBroadcast(new Intent(ACTION_STOP));

意向服务

public class UsageRecorderService extends IntentService {
  private static final String TAG  = "UsageRecorderService";
  String ACTION_STOP = "com.xxx.UsageRecorderService.ACTION_STOP";
  boolean stop;

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

  private BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override public void onReceive(Context context, Intent intent) {
      if (ACTION_STOP.equals(intent.getAction())) {
        stop = true;
      }
    }
  };

  @Override public void onCreate() {
    super.onCreate();
    IntentFilter intentFilter = new IntentFilter(ACTION_STOP);
    registerReceiver(receiver, intentFilter);
  }

  @Override
  protected void onHandleIntent(Intent intent) {
    Log.i(TAG,"onHandleIntent");
    while (true && !stop) {
      Log.i(TAG,"----running----");
      //UsageRecorder.recordUsages(this, false);
      SystemClock.sleep(10000);
    }
  }

  @Override public void onDestroy() {
    super.onDestroy();
    unregisterReceiver(receiver);
  }
}
于 2014-12-13T14:40:20.257 回答
0

IntentService 旨在仅在处理了工作队列中存在的所有请求时才停止自身。Android 在处理完所有启动请求后停止服务。

于 2017-06-08T05:58:27.790 回答