【问题标题】:Logout and Close all activities in Android注销并关闭 Android 中的所有活动
【发布时间】:2013-09-25 11:48:36
【问题描述】:
Login > HomePage ->Activity1 ->Activity2->Activity3

如果我曾经转到 Activity3,然后从那里转到主页。 从那里我试图注销。它让我回到登录页面,但如果我按下手机的后退按钮,它会显示所有以前的活动。请帮助我了解如何做到这一点。

这是我尝试过的

logout.setOnClickListener(new OnClickListener() {    
    @Override
    public void onClick(View arg0) {
        SharedPreferences myPrefs = getSharedPreferences("SelfTrip", MODE_PRIVATE);
        SharedPreferences.Editor editor = myPrefs.edit();
        editor.clear();
        editor.commit();
        Log.d(TAG, "Now log out and start the activity login");
        Intent loginPageIntent = new Intent(getApplicationContext(), LoginPage.class);
        loginPageIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
        loginPageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(loginPageIntent);

    }
});

【问题讨论】:

标签: android android-intent


【解决方案1】:

Login 活动需要在 Manifest 文件中有 android:launchMode="singleTop"。这里是 the link 用于堆栈和返回堆栈。

您还需要删除 loginPageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);,因为这将创建一个新任务并以 root 身份登录。

【讨论】:

  • 在设备后退按钮上单击所有以前的相同问题都在显示
  • 更新了答案。您需要删除Intent.FLAG_ACTIVITY_NEW_TASK 标志
  • 对设备返回按钮没有影响之前所有的都在显示
  • 如果您将getApplicationContext() 替换为CurrentActivity.class - CurrentActivity 是您当前的活动类吗?
  • 还有一件额外的事情:你所有的活动必须在同一个任务上。你怎么开始ActivityX?每次显示新活动时都不应该有Intent.FLAG_ACTIVITY_NEW_TASK,因为这会创建一个新任务
【解决方案2】:
// check sharedPreferences in all activities
// when you press back button then it will close activity
@Override
protected void onResume() {
    super.onResume();
    int userId = sharedPreferences.getInt(Login.user_id, 0);

    if(userId==0){
        finish();
    }
}

【讨论】:

    【解决方案3】:

    您可以简单地强制该活动不在您的后台留下历史记录。这可能会引起麻烦,但只要您的活动被称为线性,就应该可以正常工作。

    将带有 noHistory 的行添加到清单中:

    <activity
            android:name="com.example.MainActivity"
            android:label="@string/app_name"           
            android:screenOrientation="portrait"
    
            android:noHistory="true" >
    </activity>
    

    【讨论】:

      【解决方案4】:

      您可以使用另一种方式,即在活动类型的数组列表中添加活动并从任何其他活动中完成您想要的活动。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-01
        • 2020-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-30
        相关资源
        最近更新 更多