注销并关闭Android中的所有活动

3
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);

    }
});

请检查我的答案这里,希望对您有所帮助。 - Dmila Ram
4个回答

3
// 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

Login页面在清单文件中需要添加android:launchMode="singleTop"属性。下面是有关任务和返回栈的链接

您还需要删除loginPageIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);,因为这将创建一个新任务并将Login设置为根。


在设备的返回按钮上点击时,所有先前的问题都会显示相同的问题。 - user2568702
已更新答案。您需要删除 Intent.FLAG_ACTIVITY_NEW_TASK 标志。 - gunar
如果您将 "getApplicationContext()" 替换为 "CurrentActivity.class",其中 "CurrentActivity" 是您当前的活动类,会怎样呢? - gunar
Intent newIntent = new Intent(getApplicationContext(), ActivityNew.class); startActivity(newIntent); 这是我启动每个活动的方式。 - user2568702
如何确保所有活动都在同一个任务中? 将“getApplicationContext()”替换为当前活动实例... 因为每次都有其他上下文。 - gunar
显示剩余4条评论

1
你可以简单地强制活动在后台不保留历史记录,这可能会引起问题,但只要你的活动被称为线性,就应该能正常工作。
在清单中添加没有历史记录的行。
<activity
        android:name="com.example.MainActivity"
        android:label="@string/app_name"           
        android:screenOrientation="portrait"

        android:noHistory="true" >
</activity>

0

你可以使用另一种方式,即将活动添加到类型为activity的arraylist中,并从任何其他活动完成所需的活动。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接