从Firebase推送通知发送时,在通知单击时显示警报对话框

时间:2018-01-26 08:17:27

标签: android firebase notifications firebase-cloud-messaging firebase-notifications

我在我的项目中使用firebase推送通知。但是每当我点击通知时,总会显示 else 部分。我想在点击通知时在该对话框中显示通知文本。

以下是NotifService.class中的代码:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "FCM Service";
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        NotificationCompat.Builder mBuilder =   new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.icon_main)
                .setContentTitle("Update from Refer Ncert")
                .setContentText(""+remoteMessage.getNotification().getBody())
                .setAutoCancel(true)
                .setLights(Notification.DEFAULT_LIGHTS,1000,20000)
                .setVibrate(new long[] { 1000, 1000})
                .setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra("notifmsg",remoteMessage.getNotification().getBody());
        PendingIntent pi = PendingIntent.getActivity(this,0,intent,Intent.FLAG_ACTIVITY_NEW_TASK);
        mBuilder.setContentIntent(pi);
        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(0, mBuilder.build());
    }
}

以下是MainActivity onCreate()中显示通知的代码:

String notifmsg=getIntent().getStringExtra("notifmsg");

    if(notifmsg != null){
        new SweetAlertDialog(this)
                .setTitleText("Hello Readers!")
                .setContentText(notifmsg)
                .show();
    }
    else{
        new SweetAlertDialog(this)
                .setTitleText("Welcome Back")
                .setContentText("Continue reading your previous book by clicking on RECENT BOOK button below.")
                .show();
    }

2 个答案:

答案 0 :(得分:0)

据我所知,你定义了意图,但你没有"发送"它

在定义pendingIntent之后,将其添加到代码中,它应该起作用:

pi.send();

答案 1 :(得分:0)

您可以使用:

Intent intent = new Intent(this, MainActivity.class);
    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)
            .setContentTitle("Notification")
            .setContentText(messageBody)
            .setContentIntent(pendingIntent);
    NotificationManager notificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notificationBuilder.build());