Sai
Sai

Reputation: 15718

How to pause handler.postDelayed() timer on Android

How can i pause the handler.postDelayed() timer using a button. So when i click the same button again the handler.postDelayed() timer should resume.

handler.postDelayed(counterz, 60);

Upvotes: 11

Views: 15891

Answers (3)

public class YourActivity extends AppCompatActivity {

    private static boolean handlerflag=false;
    private Handler handler;
    private Runnable runnable;
    private int myind=0,index=0,count=0;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_activtiy);         
        //oncreate exe only
        handlerflag=true;
        handler = new Handler();
        startyourtime(0);
 }
  private void  startyourtime(int a) {

    myind=0;
    for (index=a; index<10 ;index++) {
            myind++;
            runnable=new Runnable() {
                count++;
                @Override
                public void run() {
                          //your code here
               }
            };handler.postDelayed(runnable, Constants.TIME_LIMIT * myind);

   }
    @Override
    protected void onPause() {
        super.onPause();
        handlerflag=false;
        handler.removeCallbacksAndMessages(null);
    }
    @Override
    protected void onResume() {
        super.onResume();
        if(!handlerflag)
        {
           startyourtime(count);

        }
    }
}

Upvotes: 0

Raghunandan
Raghunandan

Reputation: 133560

Handler does not have a pause method. You need to cancel and run again.

http://developer.android.com/reference/android/os/Handler.html#removeCallbacks(java.lang.Runnable)

public final void removeCallbacks (Runnable r)

Remove any pending posts of Runnable r that are in the message queue.

When not required you need to call m_handler.removeCallbacks(m_handlerTask) to cancel the run. If you need again you need to run the the task again.

            Handler m_handler;
            Runnable m_handlerTask ;  
            m_handler = new Handler();  
            m_handlerTask = new Runnable()
           {
               @Override 
               public void run() {
                             // do something 

                    m_handler.postDelayed(m_handlerTask, 1000);    

               }
          };
          m_handlerTask.run(); // call run

Suppose you use a timer. Even timer does not have pause method.

Upvotes: 3

s.d
s.d

Reputation: 29436

Handler does not have a timer to tweak. You are posting to event-queue of a thread, where a lot of other stuff is running as well.

You can cancel posted Runnable's:

handler.removeCallbacks(counterz);

And post again, to resume.

Upvotes: 21

Related Questions