单击通知打开最小化应用程序时,如何防止调用 'onCreate'?
How to preven 'onCreate' to be called when clicking on notification to open minimized app?
在我制作的应用程序中,如果应用程序被最小化,使用下面的代码我将使用 NotificationCompat.Builder
显示通知,当我点击通知时,如果用户不在应用程序,应用程序打开。
我的问题是,当应用程序打开时,onCreate
被再次调用,这导致应用程序出现问题,而如果通过单击启动器中的图标打开应用程序,onStart
然后会被调用。那么有没有办法阻止调用onCreate
?
我尝试根据创建 PendingIntent 对象时使用的意图设置标志 (Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP
),但这没有帮助。
public static void notificatePush(Context context, int
notificationId, String tickerText, String contentTitle, String
contentText, Intent intent) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(contentTitle)
.setContentText(contentText)
.setTicker(tickerText);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);//This didn't work
PendingIntent resultPendingIntent = PendingIntent.getActivity(context, notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
mBuilder.setAutoCancel(true);
mBuilder.setOnlyAlertOnce(true);
NotificationManager notifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notifyMgr.notify(notificationId, mBuilder.build());
}
尝试将清单中 activity 的启动模式设置为此
<activity
android:name=".MyActivity"
android:launchMode="singleTop" />
说明: singleTop
activity 的新实例并不是每次都创建。如果目标任务已经有一个现有实例,则不会创建 activity 的新实例,而是已经创建的实例将接收调用意图。
查看 android documentation 启动模式,并使用适合您用例的模式。
在我制作的应用程序中,如果应用程序被最小化,使用下面的代码我将使用 NotificationCompat.Builder
显示通知,当我点击通知时,如果用户不在应用程序,应用程序打开。
我的问题是,当应用程序打开时,onCreate
被再次调用,这导致应用程序出现问题,而如果通过单击启动器中的图标打开应用程序,onStart
然后会被调用。那么有没有办法阻止调用onCreate
?
我尝试根据创建 PendingIntent 对象时使用的意图设置标志 (Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP
),但这没有帮助。
public static void notificatePush(Context context, int
notificationId, String tickerText, String contentTitle, String
contentText, Intent intent) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(contentTitle)
.setContentText(contentText)
.setTicker(tickerText);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);//This didn't work
PendingIntent resultPendingIntent = PendingIntent.getActivity(context, notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
mBuilder.setAutoCancel(true);
mBuilder.setOnlyAlertOnce(true);
NotificationManager notifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notifyMgr.notify(notificationId, mBuilder.build());
}
尝试将清单中 activity 的启动模式设置为此
<activity
android:name=".MyActivity"
android:launchMode="singleTop" />
说明: singleTop
activity 的新实例并不是每次都创建。如果目标任务已经有一个现有实例,则不会创建 activity 的新实例,而是已经创建的实例将接收调用意图。
查看 android documentation 启动模式,并使用适合您用例的模式。