单击通知(FCM)时打开对话框

时间:2018-10-01 15:52:01

标签: android firebase push-notification firebase-cloud-messaging

我想在单击通知时在对话框中显示标题和消息文本。这是带有onMessageReceived和SendNotification的代码,我正在从控制台使用fcm发送消息-

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    sendNotification(remoteMessage.getNotification().getBody());

}


private void sendNotification (String messageBody){

    Intent intent = new Intent(this ,MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);


    Uri defaultsoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    notificationBuilder.setSmallIcon(R.drawable.ic_stat_name);
    notificationBuilder.setContentTitle("Guru Nanak Dev Polytechnic College");
    notificationBuilder.setContentText(messageBody);
    notificationBuilder.setAutoCancel(true);
    notificationBuilder.setSound(defaultsoundUri);
    notificationBuilder.setContentIntent(pendingIntent);


    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0,notificationBuilder.build());

}
}

2 个答案:

答案 0 :(得分:0)

您将需要一个活动引用来显示对话框,这样:

Intent intent = new Intent(this ,MainActivity.class);
intent.putExtra("fromNotification",true);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

在MainActivity中:

Intent intent= getIntent;
        if(intent.getBooleanExtra("fromNotification",true))
        {
            // show your dialog here
        }

答案 1 :(得分:0)

在您向MainActivity发送的PendingIntent中,以EXTRA的身份发送messageBody,即

Intent intent = new Intent(this ,MainActivity.class);
intent.putExtra("data", messageBody);

现在,当用户单击通知时,它将带他们到MainActivity。在MainActivity的onCreate()中,检查此活动是从通知中打开还是在其他地方(借助于getIntent的帮助下)打开:

String notificationData = getIntent().getStringExtra("data");

//if this activity is opened from notification, it will have extra data
if(notificationData !=null){

 //now open dialog
 showDialog(notificationData);
}