Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call finish() inside onPause() but not when orientation changes

I have an app that needs to call finish when someone exits its main activity (so i do not want it to be paused), even by pressing home activity has to be finished, to handle this currently i simply call finish() in my onPause() method, since everything is done with fragments it works pretty well and gives no stability issues.

My only problem is that i cannot handle orientation changes since onPause() is called before onConfigurationChanged() (allowing me to disable this behavior when rotation occurs).

I could create a service that handles this but its way to complex.

Any idea?

like image 955
JohnUopini Avatar asked Dec 27 '22 04:12

JohnUopini


1 Answers

You can use onWindowFocusChanged event instead of onPause. This function is not called when orientation changed.

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    Log.d(TAG, "FOCUS = " + hasFocus);
    if (!hasFocus) finish();
}

But note: this event is called when activity is still visible (like onPause()), you should use onStop if you want to finish the activity when it is really and fully invisible:

private boolean isInFocus = false;

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    Log.d(TAG, "FOCUS = " + hasFocus);
    isInFocus = hasFocus;
}

@Override
public void onStop() {
    super.onStop();
    if (!isInFocus) finish();
}
like image 59
matreshkin Avatar answered Jan 18 '23 13:01

matreshkin