Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Back Button to close app

Tags:

android

I have a splash screen which leads into a main navigational screen which has animations in it to introduce the buttons. Want I want is to close the app when the back button is pressed. It currently reloads the activity (main) when the return button is called - why is this?

I looked about on the forums and one way was to use the finish() method. I tried implementing this in the main.java class like this:

public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if( keyCode == KeyEvent.KEYCODE_BACK ) 
    {     
        this.finish();

        return true;
    }
    return false;
}

But the above didn't do it - what am I doing wrong?

Cheers

UPDATE

Cheers all for swift reply but none of these works. But I think I may know why - my class only implements the onCreate() method and none others. Could this be why all the other methods are failing?

UPDATE

Hi - I sorted it but I don't, at this moment, understand why this works & the other methods don't work:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if ( keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0 ) 
    {
        // do something on back.
        moveTaskToBack( true );
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

So why would this work and the finish() method used in the onBackPressed() demonstrated by ekawas doesn't??

like image 809
Katana24 Avatar asked Jan 23 '26 03:01

Katana24


1 Answers

onBackPressed is probably getting the keydown event before your onKeyDown is.

like image 98
Ben Williams Avatar answered Jan 24 '26 18:01

Ben Williams