我正在设置其他类的对象参数,为其设置接口。现在我需要做同样的事情但延迟了一个计时器。为此,我正在使用一个被正确调用的计时器任务,但是当应该从另一个活动设置param时崩溃。如何到达?
TimerTask task = new TimerTask() {
public void run() {
anotherClass.aBridge.button_back.setVisibility(View.INVISIBLE); //working fine outside timer
}
};
Timer timer = new Timer();
timer.schedule(task, 5000);
logcat错误:
10-05 12:26:58.083: E/AndroidRuntime(9815): FATAL EXCEPTION: Timer-0
10-05 12:26:58.083: E/AndroidRuntime(9815): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
10-05 12:26:58.083: E/AndroidRuntime(9815): at android.view.ViewRoot.checkThread(ViewRoot.java:2990)
10-05 12:26:58.083: E/AndroidRuntime(9815): at android.view.ViewRoot.invalidateChild(ViewRoot.java:663)
10-05 12:26:58.083: E/AndroidRuntime(9815): at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:689)
10-05 12:26:58.083: E/AndroidRuntime(9815): at android.view.ViewGroup.invalidateChild(ViewGroup.java:2604)
10-05 12:26:58.083: E/AndroidRuntime(9815): at android.view.View.invalidate(View.java:5374)
10-05 12:26:58.083: E/AndroidRuntime(9815): at android.view.View.setFlags(View.java:4723)
10-05 12:26:58.083: E/AndroidRuntime(9815): at android.view.View.setVisibility(View.java:3183)
10-05 12:26:58.083: E/AndroidRuntime(9815): at webPush$6.run(webPush.java:274)
10-05 12:26:58.083: E/AndroidRuntime(9815): at java.util.Timer$TimerImpl.run(Timer.java:284)
答案 0 :(得分:1)
您无法从后台线程更新UI。您只能从UI线程更新UI。使用runOnUiThread(runnable_instance)
从非UI线程更新UI。
答案 1 :(得分:0)
因为计时器任务将在一个单独的线程中启动。但是UI线程创建的View
不能被任何其他人触及。正如错误所说的那样。
答案 2 :(得分:0)
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
//do ur work
}};
将上述代码添加到您的课程中 并从运行调用此方法handler.sendMessage(消息消息)