我收到了来自 Firebase 的通知,但如何显示这些通知消息并将其传输到我的主布局?



这是Firebase消息服务的代码:

public class MyFirebaseMessagingService extends FirebaseMessagingService{
private static final String TAG="MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Bundle bundle = new Bundle();
bundle.putString("msgBody", remoteMessage.getNotification().getBody());
Intent new_intent = new Intent();
new_intent.setAction("ACTION_STRING_ACTIVITY");
new_intent.putExtra("msg", bundle);
sendBroadcast(new_intent);
Log.d(TAG,"FROM:"+remoteMessage.getFrom());
//check if the message contains data
if(remoteMessage.getData().size()>0){
Log.d(TAG,"Message data:"+remoteMessage.getData());
//check if the message contains notification
if(remoteMessage.getNotification()!=null){
Log.d(TAG,"Message body:"+remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody());
}
}
}

/* * 显示通知 这是显示通知的代码 这是显示通知的代码 这是显示通知的代码 * */

private void sendNotification(String body) {
Intent intent=new Intent(this,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent=PendingIntent.getActivity(this,0/*request code*/,intent,PendingIntent.FLAG_ONE_SHOT);
//set sound notification
Uri notifictaionSound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notifiBuilder=new 
NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Firebase Cloud Messaging")
.setContentText(body)
.setAutoCancel(true)
.setSound(notifictaionSound)
.setContentIntent(pendingIntent);
NotificationManager notificationManager=
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0/*ID of 
notification*/,notifiBuilder.build());
}

在你的服务中,onMessageReceived(( 调用方法

if(remoteMessage.getNotification()!=null){
Log.d(TAG,"Message body:"+remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody());
sendMessageToActivity();
}

并将其添加为方法

private static void sendMessageToActivity(String msg) {
Intent intent = new Intent("Notification");
// You can also include some extra data.
intent.putExtra("Status", msg);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}

在您想要接收的活动中

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("Status");
//do what you want with the notification
}
};
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
mMessageReceiver, new IntentFilter("Notification"));

相关内容

  • 没有找到相关文章

最新更新