Key*_*oid 2 android fragment push-notification android-activity
我开发了一个具有Firebase推送通知功能的应用程序。我创建了一个MainActivity和五个片段A,B,C,D,E。当我单击“推送通知”消息时,我想显示片段C,当我的应用程序在屏幕上打开时,它可以正常工作。
但是,当我杀死应用程序,然后推送通知到来时,我单击了推送通知,MainActivity加载了片段A,该片段是我最初带有MainActivity的片段。
我的应用程序流程:
Splash Screen -> Login Screen (Silent Login) -> Main Activity -> Load a Specific Fragment
Run Code Online (Sandbox Code Playgroud)
我的代码:
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());
}
Run Code Online (Sandbox Code Playgroud)
对于MainActivity,如下所示:
if(getIntent() != null)
{
if (getIntent().hasExtra(ARG_NOTIFICATION_FOR))
{
//Load Fragment C
}
}
Run Code Online (Sandbox Code Playgroud)
当我单击“推送通知”图标时,应用程序从启动屏幕以静默登录方式打开->主活动->加载片段A
主要活动没有hasExtra(ARG_NOTIFICATION_FOR)
您的推送通知暂挂意图需要向活动发送参数,以确定从图标或通知中打开应用程序。
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);
Run Code Online (Sandbox Code Playgroud)
为此,您应该创建自定义通知。检出此链接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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
894 次 |
| 最近记录: |