Set activity result on back button

Many applications save/apply settings just pressing the back button instead of using the Save/Cancel approach. To achieve this, my first approach was to override the onPause  method, but it did not set either the extras nor the activity result status.

The way to achieve this is to override the onBackPressed method and do the process before calling to super.onBackPressed()

public void onBackPressed() {
Log.d(this.toString(), “onBackPressed”);
long[] ids = lstOptions.getCheckItemIds();
int days = 0;
for (long id : ids)
days += Math.pow(2, (double) id);
Log.d(this.toString(), String.format(“Selected days of week: %d”, days));

Intent intent = new Intent();
intent.putExtra(jjAlarmDefinitions.OPENREPEAT, days);
setResult(RESULT_OK, intent);

Via StackOverflow

Edit: As per this other post in Stack Overflow, this solution is only valid for Android 2.0+. If working with previous versions an alternate solution is provided there.

Posted in Sin categoría | Tagged | Leave a comment