How to pause handler.postDelayed() timer on Android

不想你离开。 提交于 2019-12-23 07:55:24

问题


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

回答1:


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.




回答2:


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.




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

        }
    }
}


来源:https://stackoverflow.com/questions/17439252/how-to-pause-handler-postdelayed-timer-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!