Android的定时器/ TimerTask的引起我的应用程序崩溃? [英] Android timer/timertask causing my app to crash?
本文介绍了Android的定时器/ TimerTask的引起我的应用程序崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
不仅是测试的code是简单的块在我mainActivity的onCreate:
Just testing out a simple block of code in my mainActivity's onCreate:
Timer timer2 = new Timer();
TimerTask testing = new TimerTask() {
public void run() {
Toast.makeText(mainActivity.this, "test", Toast.LENGTH_SHORT).show();
}
};
timer2.schedule(testing, 1000);
我得到的强制关闭的错误虽然。
I get the "force close" error though.
怎么办?
推荐答案
好了为别人谁运行到这一点,我用一个处理程序和可运行做面包,这似乎有需要的用户界面交互解决了这一问题:
Alright for anyone else who runs into this, I fixed the problem by using a Handler and Runnable to do the Toast, which seems to be needed for UI interaction:
final Handler handler = new Handler();
Timer timer2 = new Timer();
TimerTask testing = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
Toast.makeText(mainActivity.this, "test", Toast.LENGTH_SHORT).show();
}
});
}
};
timer2.schedule(testing, 1000);
我还是不明白为什么这是必要的,虽然,也许有人能解释一下吗?但是,嘿,至少这个code工作笑。
I still don't understand why this is necessary though, perhaps someone could explain? But hey at least this code works lol.
这篇关于Android的定时器/ TimerTask的引起我的应用程序崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文