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

32,341

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.

Share:
32,341
Coder1
Author by

Coder1

Updated on July 09, 2022

Comments

  • Coder1
    Coder1 almost 2 years

    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);
            } 
        }); 
    }
    
  • Coder1
    Coder1 over 8 years
    Yes I should have posted the log chat. But this worked thanks for your help!
  • sakiM
    sakiM over 6 years
    Always crash if you try to invoke click method out of UI thread. Just follow the accepted answer.
  • Mohamed Mohaideen AH
    Mohamed Mohaideen AH over 6 years
    You cannot update UI interface from outside of main thread. So you should use @amir runOnUiThread() method from external threads. Otherwise delay main thread with handler like in accepted solution.