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

放肆的年华 提交于 2019-12-22 08:32:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!