Android的:如何使用定时器 [英] Android: how to use a timer

查看:162
本文介绍了Android的:如何使用定时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一篇。

让我学习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

推荐答案

下面是我这应该能正常运行的Andr​​oid 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);        
    }
}

这篇关于Android的:如何使用定时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆