使用 onStop 进行解绑服务

Use onStop for unbinding service

我有一个 Activity,我想在不调用 onDestroy() 的情况下关闭它。所以我使用 onStop(); 看起来像

@Override
    public void onStop(){
        super.onStop();
        try{
            unbindService(mServerConn);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

我运行了代码,但 activity 在屏幕上仍然可见

你能帮我把它藏起来吗? 谢谢!

你不应该打电话给 onStop() 但你可以这样做:

Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);

这将调用 onStop() 并引导您进入主屏幕。

使用System.exit(0);关闭它而不调用onDestroy().

onStop() will be called when your activity is not visible on foreground to user.

So, if your activity is currently visible to user, then it means onStop() is yet to be called from Android Framework

你的做法是正确的。您正在 取消绑定 onStop() 中的服务,这是正确的方法。

我认为你的申请会运行正确并且不需要修改

谢谢

在那种情况下 onStop() 的用法是不正确的。如果您需要关闭 activity,请使用 finish()

Intent openStartingPoint = new Intent(this, MainActivity.class);
openStartingPoint.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(openStartingPoint);
finish();

这应该没问题。