Android:当来自通知时, Activity 被添加到已经打开的 Activity 之上并且内存增加。 如何在点击通知时清除所有以前的 Activity 甚至杀死应用程序?
以下是我构建通知的方式:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)//
.setContentTitle(notificationTitle)//
.setContentText(notificationText)//
.setSmallIcon(R.drawable.app_icon_transparent)//
.setAutoCancel(true)//
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.asd));//
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, StarterActivity.class);
resultIntent.putExtra("comingFromNotification", true);
// The stack builder object will contain an artificial back stack for
// the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(StarterActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify((int) now.getTimeInMillis(), mBuilder.build());
现在,当用户收到通知并单击它时,StarterActivity 就会启动。它启动应用程序所需的所有资源,然后启动主要 Activity 。
如果应用程序一直在运行,并且占用了 50 MB 的内存,现在内存上升到 65,这意味着前一个进程没有被终止,这个进程在它之上启动。
问题是,如果应用程序在用户单击通知的那一刻正在运行,如何终止该应用程序?
编辑:在一些类似的问题中我发现了这个
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_NEW_TASK);
这会有帮助吗?这些标志是什么意思?
EDIT2:不。那些旗帜没有帮助。内存中有一些缓存对象的应用程序进程仍然存在,RAM 再次上升。
最佳答案
您的架构不适合解决这个问题。正如您在一些评论中提到的,StarterActivity
是您的根 Activity (即:具有 ACTION=MAIN 和 CATEGORY=LAUNCHER 的 Activity ),但您没有将它保存在 Activity 堆栈中,因此您不能采取FLAG_ACTIVITY_CLEAR_TOP
的优势。
要解决您的问题,您不应在 StarterActivity
启动 MainActivity
时调用 finish()
。这将允许您使用 FLAG_ACTIVITY_CLEAR_TOP
(带或不带 FLAG_ACTIVITY_SINGLE_TOP
,具体取决于您是想使用 StarterActivity
的现有实例还是创建一个新实例)。
一旦你开始工作,你现在需要处理用户在 MainActivity
中按下 BACK 并让它返回到 StarterActivity
的问题,这显然是不是你想要的。您可以通过多种方式解决该问题,这里有 2 个示例:
将 bool 成员变量添加到
StarterActivity
。在StarterActivity.onResume()
中,在方法的最后将该变量设置为true
。在onResume()
开始时,检查变量,如果为真,则可以假设用户在MainActivity
中按下了 BACK,因此您可以调用完成()
。在
MainActivity
中覆盖onBackPressed()
而不是调用super.onBackPressed()
,而是调用startActivity()
带有一个用于StarterActivity
的Intent
,带有一个额外的名为“exit”和FLAG_ACTIVITY_CLEAR_TOP
。这将导致创建一个新的StarterActivity
实例。在StarterActivity.onCreate()
中,检查Intent
中是否存在额外的“exit”,如果存在,则表示用户从按下了 BACK >主要 Activity
。在这种情况下,您只想调用finish()
来结束您的应用程序。如果您使用此机制,请确保StarterActivity
在 list 中具有标准的launchMode
,而不是launchMode="singleTop"
。
关于Android:当来自通知时, Activity 被添加到已经打开的 Activity 之上并且内存增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27925598/