Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - onBackPressed() not working

I have an application building against Android 2.1 and I want to override the back button.

I have followed the example here:

http://android-developers.blogspot.com/2009_12_01_archive.html

And my code is as follows:


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if (Integer.parseInt(android.os.Build.VERSION.SDK) < 5
                && keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            Log.d("CDA", "onKeyDown Called");
            onBackPressed();
        }

        return true;
    }

    @Override
    public void onBackPressed() {
    Log.d("CDA", "onBackPressed Called");
        Intent setIntent = new Intent(Intent.ACTION_MAIN);
        setIntent.addCategory(Intent.CATEGORY_HOME);
        setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(setIntent); 

        return;
    }   

It works on pre 2.x devices but doesn't work on a Hero with 2.1 update-1 and a Nexus One with 2.2.

Is there somwthing I am missing from the example? Or can anyone point out why it isn't working?

I dont even get the button pressed in the logcat.

like image 738
Donal Rafferty Avatar asked Aug 24 '10 15:08

Donal Rafferty


2 Answers

Are you using onKeyUp()?

Use just onKeyDown() in Android 1.x or onBackPressed() in Android 2.x

like image 108
Jorgesys Avatar answered Oct 13 '22 23:10

Jorgesys


Some quick searching suggests you should place the Back intercept during onKeyUp(): http://developer.android.com/sdk/android-2.0.html. It's worth a try. The following code is directly from the site:

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK
            && event.getRepeatCount() == 0) {
        event.startTracking();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
            && !event.isCanceled()) {
        // *** DO ACTION HERE ***
        return true;
    }
    return super.onKeyUp(keyCode, event);
}
like image 44
gary Avatar answered Oct 13 '22 22:10

gary