Is this how to schedule a java method to run 1 second later?

后端 未结 4 693
日久生厌
日久生厌 2021-02-05 17:34

In my method, I want to call another method that will run 1 second later. This is what I have.

final Timer timer = new Timer();

timer.schedule(new TimerTask() {         


        
4条回答
  •  野性不改
    2021-02-05 18:06

    There are several alternatives. But here is Android specific one.

    If you thread is using Looper (and Normally all Activity's, BroadcastRecevier's and Service's methods onCreate, onReceive, onDestroy, etc. are called from such a thread), then you can use Handler. Here is an example:

    Handler handler = new Handler();
    handler.postDelayed(new Runnable()
    {
         @Override
         public void run()
         {
             myMethod();
         }
    }, 1000);
    

    Note that you do not have to cancel anything here. This will be run only once on the same thread your Handler was created.

提交回复
热议问题