简体   繁体   中英

Using java.util.Timer

Trying to make a timer call a method every second. I can't figure out why this code is not working. Code was taken from my activity_main.xml and MainActivity.java

activity_main:

<ToggleButton
    android:id="@+id/btnStartStop"
    android:layout_width="80dp"
    android:layout_height="50dp"
    android:layout_alignLeft="@+id/clockDisplay"
    android:layout_below="@+id/clockDisplay"
    android:layout_marginLeft="40dp"
    android:layout_marginTop="0dp"
    android:textOff="Start"
    android:textOn="Stop"
    android:onClick="toggleStartStop" />

MainActivity.java:

public void toggleStartStop(View view){
        if(((ToggleButton) view).isChecked()){
            Timer timer = new Timer("timer", true);
            TimerTask task = new startTask();
            timer.schedule(task, new Date(), 1000);
        }else{
            stopTimer();
        }
    }

class startTask extends TimerTask 
{
    public void run() 
    {
        System.out.println("inc secs var");
    }
}

For debugging, use a breakpoint or a Log.d() call to see if the timer-setup code is running. It's also better to use Log.d() than println() in general.

On Android, it's better to send a message to a Handler than use a Java Timer. The OS can manage this better, eg during the Activity lifecycle.

class UpdateHandler extends Handler {
    private static final int MSG_UPDATE = 1;
    private static final long UPDATE_INTERVAL = 1000; // msec

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what) {
            case MSG_UPDATE:
                // do stuff...
                scheduleNextUpdate();
                break;
        }
    }

    void scheduleNextUpdate() {
        sendEmptyMessageDelayed(MSG_UPDATE, UPDATE_INTERVAL);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM