停止活动中的服务

时间:2014-12-13 14:31:10

标签: 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);
      }
   }
}

为什么不停止我的服务?

3 个答案:

答案 0 :(得分: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);

另外,我建议您阅读Services guide以了解其中的内容。

答案 1 :(得分:0)

的活动:

sendBroadcast(new Intent(ACTION_STOP));

IntentService

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

答案 2 :(得分:0)

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