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

对着背影说爱祢 提交于 2019-12-05 13:43:43

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();
}

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();
    }

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"

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