我开发了一个具有 Firebase 推送通知功能的应用程序。 我创建了一个 MainActivity 和五个 fragment A、B、C、D、E。 我想显示 fragment C,当我点击推送通知消息时,当我的应用程序在屏幕上打开时它工作正常。
但是当我终止应用程序然后推送通知出现时,我点击了推送通知,MainActivity 加载了 Fragment A,这是我使用 MainActivity 的初始 Fragment。
我的应用流程:
Splash Screen -> Login Screen (Silent Login) -> Main Activity -> Load a Specific Fragment
我的代码:
private void sendNotification(String title, String messageBody, int senderId) {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra(ARG_NOTIFICATION_FOR, ConstantValues.NOTIFICATION_FOR_CHAT_SCREEN);
intent.putExtra(ARG_SENDER_ID, senderId);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0 /* Request code */, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
MainActivity 如下:
if(getIntent() != null)
{
if (getIntent().hasExtra(ARG_NOTIFICATION_FOR))
{
//Load Fragment C
}
}
当我点击“推送通知”图标时,应用程序从启动画面打开并带有静默登录 -> 主 Activity -> 加载 fragment A
主 Activity 没有 hasExtra(ARG_NOTIFICATION_FOR)
最佳答案
您的推送通知待定 Intent 需要向 Activity 发送参数以确定应用程序是从图标还是通知打开的。
Intent notificationIntent = new Intent(getApplicationContext(), YourActivity.class);
notificationIntent.putExtra("FromNotification", true);//or fragment Id
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(getApplicationContext(),notificationIndex,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(getApplicationContext(), notificationTitle, notificationMessage, pendingNotificationIntent);
您应该为此创建自定义通知。查看此链接 https://developer.android.com/training/notify-user/build-notification.html
同样在 onCreate 方法中,您应该从通知中接收数据。
protected void onCreate(Bundle bundle){
super.onCreate(bundle);
//bla bla bla
boolean fromNotification = getIntent().getBooleanExtra("FromNotification",false);
if(fromNotification){
//open fragment c
}else{
//open fragment a
}
}
关于android - 使用 Activity 和 Fragment 处理推送通知导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44891137/