这是我的第一篇。
让我学习Android的&放大器;爪哇(从ActionScript来了),而且我工作的一个项目,其中:
so I'm learning Android & Java (coming from Actionscript), and I'm working on a project where :
我想点击一个ImageView的,有ImageView的交换图像一秒钟,然后返回到原始图像。 (这是一个攻丝游戏)
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 )
听起来很容易,对不对?我花了一整天试图得到一个标准的Java定时器/ TimerTask的工作..没有运气。
sounds easy enough, right? I've spent the whole day trying to get a standard Java Timer / TimerTask to work.. no luck..
有没有更好的办法?我的意思是,有没有一个Android特定的方式做这样的事情?如果不是,那么什么是理想的方式?
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?
感谢提前家伙你所有的帮助! -g
thanks for all your help in advance guys! -g
推荐答案
下面是我这应该能正常运行的Android Timer类。它每秒发送的信号。更改时间表()调用你想要一个不同的方案。
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.
请注意,你不能改变Android的图形用户界面的东西在计时器线程,这只是在主线程允许的。这就是为什么你必须使用一个处理程序给控制返回到主线程。
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);
}
}
相关推荐
最新文章