问题
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?
回答1:
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();
}
回答2:
its simple just 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:
From your question, it seems that you only have one activity, in this case you should set a flag in the manifest instead. In your MainActivity manifest add
android:clearTaskOnLaunch="true"
回答4:
You could listen for orientation changes, and on the change event store a boolean value about it, like
boolean orientationChanging;
make this true when orientation is changing, and false afterwards, than in your onPause:
@Override
protected void onPause() {
if(!orientationChanging){
finish();
}
}
来源:https://stackoverflow.com/questions/16274182/call-finish-inside-onpause-but-not-when-orientation-changes