Auto execute message every 5 seconds

2019-09-01 19:32发布

问题:

I am new to Android. Can anyone tell me how to execute a message every 5 seconds. I have tried this code, but it's not showing anything on my emulator. What should I be doing instead?

     while(true) {     
          Toast.makeText(this, "hi", Toast.LENGTH_SHORT).show();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }          
                 }

回答1:

You should not call Thread.sleep() from the GUI thread. Never do this. Use a handler for such thing.

private Handler handler = new Handler();    
private Runnable runnable = new Runnable() {   
    public void run() {
        doStuff();
        /*
         * Now register it for running next time
         */
        handler.postDelayed(this, 1000);
    } 
};

I prefer this way to using timers because the Timer class introduces a new thread and it is now fair to do this.



回答2:

Is that the sum of your code? What are you setting your activity view to? Android implements an alarm/scheduling service which will be much more friendly to battery life than trying to implement your own.