Intercepting BACK in an Activity

I couldn’t find anything good explaining this, so I’ll post here. The pattern is that you have a parent activity that lists objects, and a sub activity that allows editing those objects. If the user hits the BACK key, we want to save their work and pass it back to the parent activity. All you need to do is override Activity.onKeyDown() as such,

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
  if (keyCode == KeyEvent.KEYCODE_BACK) {
    if (save()) {
      return super.onKeyDown(keyCode, event);
    } else {
      return false;
    }
  }
  return super.onKeyDown(keyCode, event);
}

The semantics are that if you return true, then the normal flow of the BACK key continues. Here, we call super.onKeyDown() to let the default implementation process the key press as it normally would by calling super.onKeyDown() instead of just returning true directly. If you return false, then the flow stops, and the back key is canceled. In the code above, save() might implement some logic to validate the data, and set up to return a value to the parent activity by calling setResult() with an intent,

private boolean save() {
  if (validate()) {
    Intent intent = new Intent();
    intent.putExtra("org.jtb.some.data", mData);
    setResult(Activity.RESULT_OK, intent);
    return true;
  }
  return false;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: