【发布时间】:2016-09-06 03:14:14
【问题描述】:
我最近为我的应用程序实施了通知。我一直在测试的是应用程序应该如何工作的行为。我想它会是这样的:
收到通知并通过intent打开Comments.class -> MainActivity.class -> 点击返回(退出应用程序,转到Android设备的主屏幕)-> 通过任务管理器重新打开应用程序-> 返回Comments.class
前几个步骤有效,但是当我从任务管理器打开备份应用程序时,我注意到它转到Comments.class,这似乎是我用其他 Android 应用程序测试过的预期行为。
但是,我的Comments.class 的一些属性没有被设置,我知道这是因为我的Comments.class 的onCreate 方法没有被调用。有什么理由不会发生这种情况吗?这是我的尝试:
NotificationService.java:
Intent resultIntent = new Intent(context, Comments.class);
Intent backIntent = new Intent(context, MainActivity.class);
backIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//Set a random notification Id for each notification so that if you get multiple, the first does not get replaced.
Random random = new Random();
int notificationId = random.nextInt(9999 - 1000) + 1000;
PendingIntent pendingIntent = PendingIntent.getActivities(context, notificationId, new Intent[] { backIntent, resultIntent}, PendingIntent.FLAG_ONE_SHOT);
//When the notification is actually clicked on
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, notificationBuilder.build());
这首先创建通知并通知应用程序的用户。然后Comments.java 的onCreate 函数被调用,当我点击Notification 时,这是预期的。然后,我单击返回,它只是导航回MainActivity,如下所示:
Comment.java:
@Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
然后,MainActivity.java 被调用并创建,这一切都很好。如果我再次点击MainActivity.java,则执行以下代码:
来自MainActivity.java
@Override
public void onBackPressed() {
super.onBackPressed();
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
这会将我带回设备的主屏幕。但是,我的应用程序的一个实例仍在后台运行,当我在后台单击我的应用程序并将其置于前台时,我被导航回Comments.java,但因为Comments.java 的onCreate 方法是未调用,Activity 的某些细节未初始化。知道为什么会这样吗?
任何帮助将不胜感激。谢谢!
【问题讨论】:
标签: java android android-intent notifications onbackpressed