【发布时间】:2017-02-04 11:58:13
【问题描述】:
我正在尝试在同一活动中使用PendingIntent。如果MainActivity 已经在运行并且应用程序接收到通知,则当单击此通知时,它应该加载TestFragment 类,但这里不是这种情况,单击通知时没有任何反应。
Intent intent = new Intent(mContext, MainActivity.class);
intent.putExtra("NOTIFICATION", "notify");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Long.toString(System.currentTimeMillis()));
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new NotificationCompat.Builder(mContext)
.setContentIntent(pendingIntent)
.setContentTitle(title)
.setSmallIcon(R.drawable.logo)
.setLargeIcon(bitmap)
.setPriority(Notification.PRIORITY_MAX)
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(1, notification);
但是当我只将此代码用于Intent 和PendingIntent 时,我可以加载TestFragment,但它会创建两次活动。它将 TestFragment 加载到默认视图之上。
Intent intent = new Intent(mContext, MainActivity.class);
intent.putExtra("NOTIFICATION", "notify");
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
MainActivity.class onCreate()
String notificationIntent = getIntent().getStringExtra("NOTIFICATION");
if(notificationIntent != null) {
if (notificationIntent.equals("notify")) {
TestFragment fr = new TestFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, fr);
fragmentTransaction.commit();
}
} else {
//default view
}
【问题讨论】:
-
onNewIntent长什么样子? -
@pskink 我没有覆盖 onNewIntent
-
onNewIntent 如果活动在其包中将 launchMode 设置为“singleTop”,或者客户端在调用 startActivity(Intent) 时使用了 FLAG_ACTIVITY_SINGLE_TOP 标志,则会调用此方法。在任何一种情况下,当活动在活动堆栈的顶部而不是正在启动的活动的新实例时重新启动时,onNewIntent() 将在具有用于重新启动的 Intent 的现有实例上调用它。
-
我希望你知道现在该做什么
-
@pskink 谢谢!我想通了。
标签: android android-fragments android-intent android-pendingintent