How to safely finish an Activity in the onResume() method?
Asked Answered
F

3

7

My activity's onResume() reads off some "extras" data from the Intent that started it and updates the UI accordingly.

I'd like to add error handling: if the data in the Intent is missing/corrupted, the activity displays a Toast and finishes.

Can I simply call finish() in the onResume() method? I'm worried about some unexpected things given that both are related to the life cycle.

If there are other better ways, I'm interested in these too, but the above seems simplest.

Thanks!

Frowst answered 10/5, 2011 at 15:17 Comment(0)
A
5

It is safe for an Activity to self-terminate by calling finish() at any time without it having any detrimental effect.

Obviously you have to be sure you have saved any required settings/data before calling finish() but that goes without saying and is entirely your responsibility based on your Activity design.

Agglutinogen answered 10/5, 2011 at 16:35 Comment(0)
S
1

Calling finish() in onResume() should be fine. But why do you do the error handling in onResume() and not in onCreate()?

Sweettempered answered 10/5, 2011 at 15:29 Comment(1)
Thanks for that! Actually, having looked at my Activity again, I could probably do it in onCreate().Dripstone
A
0

I've encountered unpredictable results when calling finish() directly from onActivityResult(), onResume() or onPostResume(). This was on a Nexus 7 with stock Android 4.4.2.

The solution I found was calling finish() later using a Runnable:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        Handler handler = new Handler();
        handler.post(new Runnable() {
            @Override
            public void run() {
                setResult(RESULT_OK);
                finish();
            }
        });
    }
}
Antagonize answered 28/4, 2014 at 12:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.