Call finish () inside onPause (), but not when changing orientation

I have an application that needs to call the finish line when someone exits from their main action (therefore, I do not want it to be paused ), even if pressing home activity has to be completed, to handle it now I just call finish() in my onPause() method, since everything is done using fragments, it works very well and does not give stability problems.

My only problem is that I cannot handle orientation changes since onPause() is called before onConfigurationChanged() (letting me turn this behavior off during rotation).

I could create a service that can handle this, but it will be harder.

Any idea?

+4
source share
4 answers

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

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

But note: this event is fired when the activity is still visible (for example, onPause ()), you should use onStop if you want to end the action when it is really and completely 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(); } 
+7
source

its easy to do:

 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); display = ((WindowManager) getSystemService(WINDOW_SERVICE)) .getDefaultDisplay(); orientation = display.getOrientation(); } 

 @Override protected void onPause() { // TODO Auto-generated method stub int orientation_ = display.getOrientation(); if (orientation_ != orientation) { finish(); } Log.e("hello=---->", "onPause"); super.onPause(); } 
+3
source

From your question, it seems that you have only one action, in which case you should set the flag in the manifest instead. In the MainActivity manifest, add

 android:clearTaskOnLaunch="true" 
0
source

You can listen for orientation changes, and in a change event, a Boolean value, for example

 boolean orientationChanging; 

make it true when the orientation changes and then false than in your onPause:

 @Override protected void onPause() { if(!orientationChanging){ finish(); } } 
0
source

All Articles