Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
571 views
in Technique[技术] by (71.8m points)

java - How to automatically Click a Button in Android after a 5 second delay

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.

Here is my code:

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);
        } 
    }); 
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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);

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...