如何在Android应用程序中正确实现android.os.Handler类而不是Timer?
所以我想在我的 Anroid 程序中实现 Timer,我发现更好的方法是使用 Handler 类。
首先,我决定使用 Handler 编写最简单的程序 - 文本在 1 秒后设置。我是 Android 的初学者,所以我在网上浏览了一些教程,尤其是 http://developer.android.com/resources/articles/timed-ui-updates.html ,但我的应用程序仍然显示错误(“应用程序 mTimer 已停止”)。
那么有人能指出我到底在哪里犯了错误吗?我将不胜感激,这是代码:
public class mTimer extends Activity {
TextView tv;
Button button1,button2;
Handler mHandler;
private Runnable myTask = new Runnable() {
public void run() {
tv.setText("text");
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1=(Button)findViewById(R.id.button1);
tv=(TextView)findViewById(R.id.textView1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mHandler.postDelayed(myTask, 100);
}
});
}
}
So I wanted to implement Timer in my Anroid program and I found out the better way to do that is using Handler class.
First I decided to write the simplest program using Handler - the text is set after 1 second. I'm totall beginner in Android, so I went through some tutorials on web especially that one http://developer.android.com/resources/articles/timed-ui-updates.html , but still my application shows error ("application mTimer stopped").
So could anyone point out where exactly am I making mistake? I would be gratefull, here's the code:
public class mTimer extends Activity {
TextView tv;
Button button1,button2;
Handler mHandler;
private Runnable myTask = new Runnable() {
public void run() {
tv.setText("text");
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1=(Button)findViewById(R.id.button1);
tv=(TextView)findViewById(R.id.textView1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mHandler.postDelayed(myTask, 100);
}
});
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该在
onCreate
方法中至少使用mHandler = new Handler();
之类的代码来初始化您的Handler
。请注意,
myTask
任务将在 UI 线程上运行,因为您的处理程序是在API Docs for
Handler.postDelayed
中声明的:You should initialize your
Handler
in youronCreate
method with at least a code likemHandler = new Handler();
.Note, that the
myTask
task will be run on the UI thread, since your handler is declared thereAPI Docs for
Handler.postDelayed
: