如何在延迟5秒后自动点击Android中的按钮 [英] How to automatically Click a Button in Android after a 5 second delay
问题描述
我有一个小型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.
要做你想要的你真的不需要另一个线程。您可以使用处理程序
和延迟的 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中的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!