【发布时间】:2016-09-08 05:26:26
【问题描述】:
我想在点击推送通知消息时打开特定片段。在我的情况下,片段在通知发生时打开。但我想在点击通知消息时打开片段,而不是收到消息。
这是我的 sendNotification() 方法:-
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("data", "fromoutside");
getApplicationContext().startActivity(intent);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder mBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(getNotificationIcon())
.setContentTitle("Telepoh")
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
mBuilder.setContentIntent(contentIntent);
mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
mBuilder.setAutoCancel(true);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
这是我在打开片段的 MainActivity 中覆盖的 onNewIntent() 方法:-
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Fragment fragment = new NotificationActivity();
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).addToBackStack(null).commit();
}
我的问题是我想在点击推送通知消息时打开这个片段,但在我的情况下,当推送通知消息到达时片段是打开的。
【问题讨论】:
-
在
sendNotification()方法中为意图添加一个动作(确保它是唯一的)。然后在onNewIntent()中获取 Action 并仅在正确意图到达时打开片段。 -
我试过这个方法,但它不起作用!如果我做错了,请你写一些代码。
-
添加您的
AndroidManifest.xml。 -
请检查更新后的代码。在我的主要活动中,我添加了 android:launchMode="singleTop"。
-
只是想知道,为什么要创建一个已经打开的新片段?我想我可能误解了这个问题
标签: android android-intent push-notification google-cloud-messaging android-pendingintent