Solenoid
Solenoid

Reputation: 2381

Android not finishing activity when told to

I have a scenario where the user can either click on the back button to access the previous activity or do whatever else and the activity will end itself (such as an incoming call, click on the power button, switch app...). These calls must return different results to the previous activity (called with startActivityForResult), it's either a graceful quit or a messy one according to which actions will be taken...

Now when Android calls onBackPressed it will always also call onStop too, not the other way round though. So I'd like for my app to finish when I call onBackPressed without calling onStop, calling finish() inside onBackPressed doesn't work.

Some code to illustrate my problem:

@Override
public void onStop() {
    // this gets called no matter what, I don't like that
    Log.i(TAG, "Canceled");
    setResult(RESULT_CANCELED, new Intent());
    finish();
    super.onStop();
}

@Override
public void onBackPressed() {
    Log.i(TAG, "User ended activity");
    setResult(RESULT_OK, new Intent());
    finish();
    super.onBackPressed();
}

Upvotes: 0

Views: 154

Answers (1)

Sam
Sam

Reputation: 86948

If you don't want to call setResult() repeatedly as the app closes use Activity.isFinsihing():

@Override
public void onStop() {
    // Now this is only called if Activity is not finishing already
    if(!isFinishing()) {
        Log.i(TAG, "Canceled");
        setResult(RESULT_CANCELED, new Intent());
        finish();
    }
    super.onStop();
}

Upvotes: 2

Related Questions