runOnUiThread在android中抛出错误

时间:2014-03-14 07:31:42

标签: android timer timertask

我在这里做错了什么?

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
                }
            });

        }
    };
}

}

它强调runOnUiThread红色并给我以下错误: the method runOnUiThread(new runnable(){}) is undefined for the type new TimerTask(){}

1 个答案:

答案 0 :(得分:4)

runOnUiThread是Activity类的一种方法。需要一个上下文。

MainActivity.this.runOnUiThread(new Runnable() {

如果您在非Activity类中有代码,则需要将一个Activity上下文传递给非活动类的构造函数。然后你可以使用相同的。