【发布时间】:2014-03-17 06:33:39
【问题描述】:
我正在尝试创建一个可以在我的应用程序中使用计时器的通用类。
我想向它传递一个必须在 UI 线程上运行的函数,因为这个计时器主要用于 GUI。
这是我到目前为止所拥有的,但是我不确定如何实现它的回调部分,并且我在使用 runOnUiThread 时遇到了问题,因为如果我通过一个上下文它希望我将它转换为一个活动类型.但是我希望能够从任何活动中调用这个计时器类。
这是我的课:
public class AutoTimer extends Timer {
Timer autoRefreshTimer;
TimerTask task;
public AutoTimer(int delay, int period, Context context) { // todo add
// callback as
// param
autoRefreshTimer = new Timer();
createTask(context);
autoRefreshTimer.scheduleAtFixedRate(task, delay, period);
}
private void createTask(final Context context) {
task = new TimerTask() {
@Override
public void run() {
/*
* context.runOnUiThread(new Runnable() {
*
* @Override public void run() { //run callback method from the
* calling activity } });
*/
}
};
}
}
你能帮我解决我的两个问题吗?
所以我想这样称呼它:
AutoTimer timer = new AutoTimer(0,1000,Activity.this,callbackfuntion());
【问题讨论】: