在我的Android应用程序中我正在使用Timer schedule.but得到Timer-0致命异常如下所示。我可以删除它。我也提到了下面的代码 -
01-28 13:44:41.142: E/AndroidRuntime(1307): FATAL EXCEPTION: Timer-0
01-28 13:44:41.142: E/AndroidRuntime(1307):android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
01-28 13:44:41.142: E/AndroidRuntime(1307): at android.view.ViewRoot.checkThread(ViewRoot.java:2932)
01-28 13:44:41.142: E/AndroidRuntime(1307): at android.view.ViewRoot.invalidateChild(ViewRoot.java:642)
01-28 13:44:41.142: E/AndroidRuntime(1307): at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:668)
01-28 13:44:41.142: E/AndroidRuntime(1307): at android.view.ViewGroup.invalidateChild(ViewGroup.java:2511)
01-28 13:44:41.142: E/AndroidRuntime(1307): at android.view.View.invalidate(View.java:5279)
01-28 13:44:41.142: E/AndroidRuntime(1307): at android.view.View.setBackgroundDrawable(View.java:7626)
01-28 13:44:41.142: E/AndroidRuntime(1307): at android.view.View.setBackgroundResource(View.java:7535)
01-28 13:44:41.142: E/AndroidRuntime(1307): at com.example.iqtest.PlayGame$1.run(PlayGame.java:61)
01-28 13:44:41.142: E/AndroidRuntime(1307): at java.util.Timer$TimerImpl.run(Timer.java:284)
和代码是 -
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.next);
but1=(Button) findViewById(R.id.b1);
but2=(Button) findViewById(R.id.b2);
but3=(Button) findViewById(R.id.b3);
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
Random rand=new Random();
int num=rand.nextInt(9)+1;
num = rand.nextInt(buttonIds.length);
int buttonId = buttonIds[num];
Button bb=(Button) findViewById(buttonId);
Drawable a=bb.getBackground();
if(getResources().getDrawable(R.drawable.happy).equals(a))
bb.setBackgroundResource(R.drawable.happy);
else
bb.setBackgroundResource(R.drawable.whoa);
}
},0, 1000);
}
答案 0 :(得分:5)
使用runOnUiThread更新来自Timertask run Method的UI元素:
myTimer.schedule(new TimerTask() {
@Override
public void run() {
Current_Activity.this.runOnUiThread(new Runnable() {
public void run() {
// update UI here
}
});
}
},0, 1000);
答案 1 :(得分:2)
您可以使用CountDownTimer
代替Timer
:
Timer timer = new CountDownTimer(Long.MAX_VALUE, 1000) {
public void onTick(long millisUntilFinished) {
// the code in the method run
}
public void onFinish() {
}
};
将在UI线程中调用方法onTick
和onFinish
。
要使计时器开始执行其操作,请运行:timer.start()
答案 2 :(得分:0)
这很简单,你正在安排定时器,但从不取消它。因此,预定的任务将在队列中并等待轮到它。到那时它应该被执行你的Activity可能不在前台而且它无法找到视图。所以它抛出了致命的例外。为了解决上述问题,您需要通过调用myTimer.cancel()
来取消任务,无论何时您从该特定活动开始。
否则
使用Handler类。
答案 3 :(得分:0)
runOnUiThread(new Runnable() {
public void run() {
//stuff that updates ui
}
});
试试这个
也看看
Android "Only the original thread that created a view hierarchy can touch its views."
Only the original thread that created a view hierarchy can touch its views