Android: how to use a timer

2019-02-14 22:42发布

this is my first post..

so I'm learning Android & Java (coming from Actionscript), and I'm working on a project where :

I'm trying to click an ImageView, have that ImageView swap images for a second, then return to the original image. ( this is for a tapping game )

sounds easy enough, right? I've spent the whole day trying to get a standard Java Timer / TimerTask to work.. no luck..

is there a better way? I mean, is there an Android specific way to do something like this? If not, then what is the ideal way?

thanks for all your help in advance guys! -g

2条回答
我命由我不由天
2楼-- · 2019-02-14 23:27

Here is my Android timer class which should work fine. It sends a signal every second. Change schedule() call is you want a different scheme.

Note that you cannot change Android gui stuff in the timer thread, this is only allowed in the main thread. This is why you have to use a Handler to give the control back to the main thread.

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.os.Handler;
import android.os.Message;

public class SystemTimerAndroid {
    private final Timer clockTimer;

    private class Task extends TimerTask {
        public void run() {
            timerHandler.sendEmptyMessage(0);
        }
    }

    private final Handler timerHandler = new Handler() {
        public void handleMessage (Message  msg) {
            // runs in context of the main thread
            timerSignal();
        }
    };

    private List<SystemTimerListener> clockListener = new ArrayList<SystemTimerListener>();

    public SystemTimerAndroid() {
        clockTimer = new Timer();
        clockTimer.schedule(new Task(), 1000, 1000);
    }

    private void timerSignal() {
        for(SystemTimerListener listener : clockListener)
            listener.onSystemTimeSignal();      
    }

    public void killTimer() {
        clockTimer.cancel();
    }

    @Override
    public void addListener(SystemTimerListener listener) {
        clockListener.add(listener);        
    }
}
查看更多
贼婆χ
3楼-- · 2019-02-14 23:32

One way could be creating a Pipeline thread(a normal thread with Looper.prepare()). Post delayed messages to its message loop. In the Message Handler, swap the images. See the following list of tutorials to understand the entities involved:
Handler Tutorial
Handler: documentation
Android guts into Loopers(Pipeline threads) and Handlers

Hope that helps.

查看更多
登录 后发表回答