我正在开发一个Android应用程序。
有一个网络管理面板,在那里,我可以强迫一个应用程序用户退出应用程序。这个功能很好用。当前的应用程序用户被迫退出,并收到一条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
}发布于 2019-07-11 13:35:59
将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()
}您可以在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();
}https://stackoverflow.com/questions/56990428
复制相似问题