android - Intent.FLAG_ACTIVITY_CLEAR_TOP 即使应用程序在后台也会导致 Activity 弹出?

标签 android android-activity android-intent

我使用的是 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/

相关文章:

android - 无法从 Leakcanary 的泄漏报告中检测到引用

android - 在 GameThread (android) 中开始由 bool 值触发的新 Activity

java - 错误/dalvikvm(1399) : Could not find class 'maptest.xyz.com.maps' , 从方法 maptest.xyz.com.maptest$1.onClick 引用

java - Activity 方向在后台发生变化

android - 在模拟器中找不到处理地理 Intent 的 Activity

android - 空 NFC 标签属于哪种 Intent 类型?

android - 如何在android中的 GridView 中显示选择的图像

android - 从 api 服务器获取 400 请求

android - 我需要编辑 Android 许可库中的 ServerManagedPolicy 吗?

android - 即使调用了 setResult,也不会调用 onActivityResult