Run loop every second java

后端 未结 5 1487
你的背包
你的背包 2020-12-29 14:54
int delay = 1000; // delay for 1 sec. 
int period = 10000; // repeat every 10 sec. 
Timer timer = new Timer(); 
timer.scheduleAtFixedRate(new TimerTask() 
    { 
            


        
5条回答
  •  心在旅途
    2020-12-29 15:14

    There several mistakes you have done:

    1. You should never invoke Thread.sleep() on the main thread (and you should never block it for a long time as well). Once main thread is blocked for more then 5 seconds, an ANR (application not responding) happens and it is force closed.

    2. You should avoid using Timer in android. Try Handler instead. Good thing about handler is that it is created on the main thread -> can access Views (unlike Timer, which is executed on its own thread, which cannot access Views).

      class MyActivity extends Activity {
      
          private static final int DISPLAY_DATA = 1;
          // this handler will receive a delayed message
          private Handler mHandler = new Handler() {
              @Override
              void handleMessage(Message msg) {
                  if (msg.what == DISPLAY_DATA) displayData();
              }
           };
      
           @Override
           void onCreate(Bundle b) {
               //this will post a message to the mHandler, which mHandler will get
               //after 5 seconds
               mHandler.postEmptyMessageDelayed(DISPLAY_DATA, 5000);
           }
       } 
      

提交回复
热议问题