2

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?

Mousa Jafari
  • 677
  • 1
  • 6
  • 21
  • 1
    The answer: http://stackoverflow.com/questions/8709989/how-to-stop-intentservice-in-android – eleven Dec 13 '14 at 14:35

3 Answers3

2

This code would work

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

}

You can use stopService

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

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

gio
  • 4,950
  • 3
  • 32
  • 46
0

Activity:

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);
  }
}
Jerome
  • 1,749
  • 1
  • 14
  • 40
0

An IntentService is designed to stop itself only when all the requests present in the work queue have been handled.Android stops the service after all start requests have been handled.

Shinoo Goyal
  • 601
  • 8
  • 10