Tvd
Tvd

Reputation: 4601

Not to call onDestroy on onBackPressed

I don't want my acivity to get destroyed when Back button is pressed. My app is compatible from 1.6 SDK's. Referring to http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html and Override back button to act like home button, I opted the following code :

    @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
                // For versions lower than 2.0     
    if (Utility.buildDet.getDeviceBuildAPI() <= Utility.buildDet.getBuildApi() 
            && keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
        onBackPressed();
    return super.onKeyDown(keyCode, event);
}

      // In any version, this function will be called
public void onBackPressed() {
    // This will be called either automatically for you on 2.0    
    // or later, or by the code above on earlier versions of the platform.
    Log.i(TAG, "##### BACK KEY IS PRESSED");
    this.moveTaskToBack(true);  // on false, it shows moveTaskToBack: 11
    return;
}

When I press Back button, I these logs

: ##### BACK KEY IS PRESSED
 INFO/ActivityManager(51): moveTaskToBack: 10
: !!!!!!! Into onPause
: !!!!!!! Into onStop
: !!!!!!! Into DESTROY

I have not overridden moveTasToBack(). Anu clu what do I do to not get destroyed when back button is pressed. Maybe I want to just ignore the button or hide the activity.

Any clue, why it is not working as expected.

Thanks

Upvotes: 1

Views: 4505

Answers (4)

Lune
Lune

Reputation: 351

@Override
public void finish() {
    //super.finish();
    moveTaskToBack(true);
}

Upvotes: 1

s.d
s.d

Reputation: 29436

Capturing back key won't solve this. Activity Life cycle in android is best left to the System. System will kill your activity whenever it wants.

Upvotes: 0

pawelzieba
pawelzieba

Reputation: 16082

Why do you want to change standard system bahaviour? Android system can destroy activity or not. It should depend only on the system. You probably want to do something that can be done differently. Maybe you need services or implement saving state of activity?

Upvotes: 2

Adil Soomro
Adil Soomro

Reputation: 37729

public boolean onKeyDown(int keyCode, KeyEvent event)  
{

     if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
     {

        this.moveTaskToBack(true);
           return true;
      }

    return super.onKeyDown(keyCode, event);
}

Upvotes: 10

Related Questions