问题描述
我有一个小的 Android 应用程序,它会在 5 秒后自动点击按钮.我使用了 performClick();
但这不起作用.当计时器归零时,它就会崩溃.
I have a small Android application that automatically clicks the button after 5 seconds. I have used performClick();
but this does not work. When the timer gets to zero it simply crashes.
这是我的代码:
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.local);
getActionBar().setIcon(R.drawable.menu_drop);
buttonClick();
Thread timer = new Thread(){
public void run(){
try{
sleep(5000);
} catch (InterruptedException e){
e.printStackTrace();
}finally{
button1.performClick();
}
}
};
timer.start();
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void buttonClick() {
button1 = (Button) findViewById(R.id.button);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(TestButton2.this, LocationView.class);
startActivity(i);
}
});
}
推荐答案
您应该发布包含错误消息的 logcat,但一个问题可能是您正在从 UI 线程访问 UI 元素,这不是一个好主意.
You should post your logcat that includes the error message but one issue might be that you are accessing a UI element off the UI thread which isn't a good idea.
要做你想做的事,你真的不需要另一个线程.您可以使用 Handler
和延迟的 Runnable
代替,如下所示.
To do what you want you really don't need another thread. You can use a Handler
and a delayed Runnable
instead like below.
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
button1.performClick();
}
}, 5000);
这将安排 Runnable
在 5 秒后在 UI 线程上执行.如果仍然崩溃,请从 logcat 发布堆栈跟踪.
This will schedule the Runnable
to be executed on the UI thread after 5 seconds. If that still crashes post the stack trace from logcat.
这篇关于如何在 5 秒延迟后自动单击 Android 中的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!