How to safely finish an Activity in the onResume() method?
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 开发者_JAVA技巧simplest.
Thanks!
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.
Calling finish()
in onResume()
should be fine. But why do you do the error handling in onResume()
and not in onCreate()
?
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();
}
});
}
}
精彩评论