首页 文章

Android:如果从Recent Task启动应用程序,则Activity正在使用旧意图

提问于
浏览
14

我正在实施GCM . 我的应用程序有两个活动,比如 AB . 我正在使用此代码从NotificationBar启动 B

long when = System.currentTimeMillis();
NotificationManager notificationManager =
    (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
String title = context.getString(R.string.app_name);        
Notification notification = new Notification(R.drawable.app_notification_icon, "De Centrale", when);//message
Intent notificationIntent = new Intent(context, B.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); //|Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
notification.setLatestEventInfo(context, title, msg, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);

NotificationBar用Intent打开Activity B ,比如'B-notification-intent',然后我使用Back按钮从 B 打开Activity A ,然后我再次从具有新Intent(例如'B-A-intent')的 A 启动 B . 我使用下面的代码:

intent = new Intent(this, B.class); 
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);              
startActivity(intent);

然后我在 B 中获得了新数据(即刷新了 B 的屏幕) . 但是,如果我按下主页按钮,然后我从最近的应用程序启动应用程序,那么我会使用'B-notification-intent'获得更长的 B 屏幕 . 相反,我想要最新的意图,即'B-A-intent' . 我在 B 中使用此代码:

@Override
protected void onCreate(Bundle b)
{
    fetchDataFromDB(getIntent());           
}

@Override
protected void onNewIntent(Intent intent)
{
    fetchDataFromDB(intent);        
}

所以任何人请帮助我获取当前的屏幕(意图) .

1 回答

  • 18

    我还注意到有时_1179993_的 onCreate() 在从最近发射时启动时会变得陈旧 Intent ,但是有一种方法可以检查它,这样你就可以适当地处理 Intent .

    protected boolean wasLaunchedFromRecents() {
        return (getIntent().getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY;
    }
    

    在我的拙见中,该标志名称很差(引用“最近”列表的其他标志实际上使用了该单词,例如 FLAG_ACTIVITY_EXCLUDE_FROM_RECENTSFLAG_ACTIVITY_RETAIN_IN_RECENTS )并且文档从未更新以反映许多流行的Android设备具有专用按钮用于最近的事实:

    此标志通常不是由应用程序代码设置的,而是由系统为您设置的,如果从历史记录启动此活动(longpress home key) .

    (注意我意识到你几年前以另一种方式解决了你的问题,但这个问题是'android old intent recent'的最佳搜索结果之一,其他相关问题都没有提到这个标志,所以希望这个答案可以帮助别人 . )

相关问题