我使用的是 Android 2.2。我有一个应用程序在一段时间不活动后注销(导致应用程序返回登录页面)。我正在为我的 Intent
使用 Intent.FLAG_ACTIVITY_CLEAR_TOP
。但是,我注意到当我的应用程序在后台并且在一段时间内处于非 Activity 状态时,登录页面突然弹出并且我的应用程序进入前台。我希望登录页面将保留在后台。当我没有为我的 Intent 使用任何标志时,这不会发生。如果我没有为我的 Intent 使用任何标志,登录页面会在后台安静地启动。但是如果不使用 Intent.FLAG_ACTIVITY_CLEAR_TOP
,我将无法清除我的历史堆栈。
为什么会这样?如何在后台安静地启动 Activity ?
下面是我的代码 fragment :
@Override //Inside a class extending AsyncTask
protected void onPostExecute(String result)
{
((GlobalApplication)getApplicationContext()).setIsLogin(false); //user is not logged in anymore
Intent intent = new Intent(this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
下面是我根据 Lars 的建议制作的代码 fragment :
@Override //Inside a class extending AsyncTask
protected void onPostExecute(String result)
{
((GlobalApplication)getApplicationContext()).setIsLogin(false); //user is not logged in anymore
Intent intent = new Intent(this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if(((GlobalApplication)getApplicationContext()).isOnBackground())
((GlobalApplication)getApplicationContext()).setPendingIntent(intent);
else
startActivity(intent);
}
@Override //overrides android.app.Activity. inside the current Activity
protected void onResume()
{
super.onResume();
Intent pendingIntent = ((GlobalApplication)getApplicationContext()).getPendingIntent();
if(pendingIntent != null)
startActivity(pendingIntent);
}
最佳答案
您是否尝试过检查您是否仍在 Activity 的 onResume 部分登录,而不是在计时器关闭时调用您的 LoginActivity(我假设您正在做的事情)?
编辑:为澄清起见,您将在预定义的时间段后(或事件发生时)将用户注销。此时您启动一个 AsyncTask,它为您的 loginActivity 创建一个 Intent ,向其添加一个标志并启动它。你的问题是你不希望 loginActivity 出现在前台,除非用户打开了应用程序。准确吗?
因为如果是的话,我会推荐使用我上面提到的 onResume 方法。每当 Activity 回到(返回)前台时,就会调用这些。为了即使用户不更改 Activity 也显示登录屏幕,您可以尝试发送广播并在您的 Activity 中收听它。
编辑:我的评论中的代码 fragment (现在格式正确):
@Override
protected void onResume() {
super.onResume();
if (!getLoggedIn())
{
startActivity(new Intent(this, LoginActivity.class));
finish();
}
}
关于android - Intent.FLAG_ACTIVITY_CLEAR_TOP 即使应用程序在后台也会导致 Activity 弹出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7632178/