RoFF
RoFF

Reputation: 559

how to stop Handler working in android?

My APP has to start some time consuming job when receiving ACTION_SCREEN_OFF, and interrupt the job when receiving ACTION_SCREEN_ON if job is still going on.

public class TimeConsumingWorkIntentService extends IntentService {
    @Override
    protected void onHandleIntent(Intent intent) {
       TimeConsumingWork();
    }
}

public class ScreenStatusReceiver extends BroadcastReceiver {
  Intent intent = new Intent(mContext, TimeConsumingWorkIntentService.class);
  @Override
  public void onReceive(Context context, Intent intent) {
      if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
          mContext.startService(intent );
      } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
          mContext.stopService(intent );
      }
  }
}

By print log of time, I find time consuming work is still going on stop the TimeConsumingWorkIntentService (when receiving ACTION_SCREEN_ON).

why ?

Upvotes: 2

Views: 1122

Answers (2)

David Wasser
David Wasser

Reputation: 95578

You can't do this like that. When you start your IntentService, it will call onHandleIntent() on a separate worker thread. That mehod then calls TimeConsumingWork(). Stopping the service will not interrupt the execution of the worker thread. It just tells the worker thread that when it has finished processing the current Intent, it should stop.

What you will need to do is to have your TimeConsumingWork() method periodically look to see if it should stop. You can do this by setting a static boolean variable and have TimeConsumingWork() periodically check this variable and quit if it is set.

You don't need to call stopService() on an IntentService as it will stop itself when it has nothing to do.

Upvotes: 0

Viswanath Lekshmanan
Viswanath Lekshmanan

Reputation: 10083

Use

// Cancel the runnable

myHandler.removeCallbacks(yourRunnable);

Ok , then you can do something like this

Runnable r = new Runnable{
public void run(){
    if(booleanCancelMember != false){
        // within this you make the call to handler and work
        // Since you block the call the handler wont get repeated
    }
  }
}

Upvotes: 3

Related Questions