调用另一个活动后终止活动

时间:2019-07-11 13:30:53

标签: android

我正在使用Android应用。

有一个Web管理面板,我可以在其中强制应用程序用户从该应用程序注销。该功能运行良好。当前的应用程序用户被迫注销,并收到一条Toast消息,通知他管理员已取消其帐户。显示登录屏幕活动。

我的问题是我想终止正在下令强制注销的活动,但是使用我当前的代码,活动并未终止。显示登录屏幕,但在后台运行第一个活动,然后一次又一次显示Toast。

这是注销功能的当前代码:

 private void logoutUser() {


        SharedPreferences prefs2 =
                getSharedPreferences(MISDATOS, Context.MODE_PRIVATE);

        SharedPreferences.Editor editor2 = prefs2.edit();
        editor2.putString("LOGEADO", "NO");
        editor2.apply();

        // Launching the login activity
        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        this.finish(); // Call once you redirect to another activity

    }

1 个答案:

答案 0 :(得分:0)

将FLAG_ACTIVITY_NEW_TASK添加到您的意图中,例如

第二件事使用addFlags而不是setFlags

private void logoutUser() {


        SharedPreferences prefs2 =
                getSharedPreferences(MISDATOS, Context.MODE_PRIVATE);

        SharedPreferences.Editor editor2 = prefs2.edit();
        editor2.putString("LOGEADO", "NO");
        editor2.apply();

        // Launching the login activity
        Intent intent = new Intent(this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
         stopActivity(); // Call once you redirect to another activity

    }

    private void stopActivity() {
       finish()
    }

Another solution

您可以在Android android:excludeFromRecents="true"文件中为活动设置android:noHistory="true"Manifest,而无需完成活动

棘手的解决方案

您可以利用活动生命周期。确保在活动之间导航时会调用onPause,但是当用户离开您的应用程序时也会调用onPause。这就是为什么我声明一个布尔值用于检查

的原因
private needFinish = false;

    private void logoutUser() {


            SharedPreferences prefs2 =
                    getSharedPreferences(MISDATOS, Context.MODE_PRIVATE);

            SharedPreferences.Editor editor2 = prefs2.edit();
            editor2.putString("LOGEADO", "NO");
            editor2.apply();

            // Launching the login activity
            Intent intent = new Intent(this, LoginActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
             needFinish = true; // Call once you redirect to another activity

        }
private void stopActivity() {
           finish()
        }


@Override
public void onPause() {
    super.onPause();
    if(needFinish) stopActivity();

}
相关问题