1

Firebase는 firebase 콘솔을 사용하고 이전처럼 GCM과 같은 서버를 사용하여 푸시 알림을 발송하는 두 가지 방법을 제공합니다. 이제 Google 서버를 GCM에서 Firebase로 번역 중이며 앱에서 FCM 알림을 받아 표시해야합니다.서버와 함께 보낸 FCM Firebase 알림을 표시하는 방법

나는 공식 firebase 웹 사이트의 구현을 완료하고 샘플 코드를 완료했지만이 부분에 붙어 있습니다. Google 서버가 푸시 알림을 Firebase에 보내고 firebase가 내 앱에 보낼 때 RemoteMessage 매개 변수가있는 onMessageReceived 메서드 알림이 전송됩니다. 메시지가 RemoteMessage 매개 변수 안에 있다는 것을 알고 있지만, 안드로이드 장치 알림 표시 줄에 알림 텍스트를 표시하는 방법을 다루는 방법에 대한 Firebase 공식 문서에서 가이드 또는 샘플 코드를 찾을 수 없습니다.

공식 가이드에서 볼 수 있듯이 RemoteMessage 매개 변수에서 문제없이 메시지를 추출하는 방법은 설명되어 있지 않습니다. 나는 당신이 안으로 검색 할 수 있고 문자열을 찾을 수 있지만 나는 이것을 정확하고 안전하게 다루는 방법에 대한 공식 가이드를 찾고 싶다. 공식 문서에서

는, 당신은 단지이 : 그런 다음 서버에서 당신을 JSON onMessageRecieve을받을 것입니다

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 /* Request code */, intent, 
       PendingIntent.FLAG_ONE_SHOT); 

     Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
     NotificationCompat.Builder notificationBuilder = 
       new NotificationCompat.Builder(this) 
         .setSmallIcon(R.drawable.ic_main) 
         .setContentTitle("FCM Message") 
         .setContentText(messageBody) 
         .setAutoCancel(true) 
         .setSound(defaultSoundUri) 
         .setContentIntent(pendingIntent); 

     NotificationManager notificationManager = 
       (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

     notificationManager.notify(0 /* ID of notification */, notificationBuilder.build()); 
    } 
+0

확인 [이] (https://stackoverflow.com/questions/45875859/fcm-onmessagereceived-not-calling-android/45880920#45880920) – Maddy

+0

좋은 포스트 나는주의 깊게 읽어 @Maddy – NullPointerException

+0

도와 드리겠습니다 :) – Maddy

답변

0

:

@Override 
public void onMessageReceived(RemoteMessage remoteMessage) {  
    // TODO(developer): Handle FCM messages here. 
    Log.d(TAG, "From: " + remoteMessage.getFrom()); 

    // Check if message contains a data payload. 
    if (remoteMessage.getData().size() > 0) { 
     Log.d(TAG, "Message data payload: " + remoteMessage.getData()); 
     // Handle message within 10 seconds  
    } 

    // Check if message contains a notification payload. 
    if (remoteMessage.getNotification() != null) { 
     Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); 
    } 

    // Also if you intend on generating your own notifications as a result of a received FCM 
    // message, here is where that should be initiated. See sendNotification method below. 
} 

그리고 (가이드에 호출되고 있지 않은)이 그 json을 파싱하고 그것으로부터 가치를 얻을 필요가있다. 당신이 파싱 된 가치를 가지고 있다면, sendNotification()과 함께 그것을 보낼 수있다. 필요한 방법과 방법

0

나는 이 내가 sendNotification에() 대신에 addNotifcation()를 사용하고 같은 하나의 일이

public class MyFirebaseMessagingService extends FirebaseMessagingService { 
private static final String TAG = "FCM Service"; 

@Override 
public void onMessageReceived(RemoteMessage remoteMessage) { 
    Log.d(TAG, "From: " + remoteMessage.getFrom()); 
    Log.d(TAG, "Notification Message Body: " + remoteMessage.getData().get("body")); 
    addNotification(remoteMessage.getData().get("body"), remoteMessage.getData().get("Nick")); 
} 

private void addNotification(String message, String title) { 
    NotificationCompat.Builder builder = 
      (NotificationCompat.Builder) new NotificationCompat.Builder(this); 
     builder.setSmallIcon(R.mipmap.ic_launcher1) 
       .setContentTitle(title) 
       .setContentText(message); 

    Intent notificationIntent = new Intent(this, app.class); 
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 
      PendingIntent.FLAG_UPDATE_CURRENT); 
    builder.setContentIntent(contentIntent); 

    // Add as notification 
    NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); 
    manager.notify(0, builder.build()); 
} 
0

먼저 onMessageReceived() showNotification

에 대한

showNotification(remoteMessage.getData()); 

기능에이

private static NotificationManager mNotificationManager; 

쓰기이 선언

public void showNotification(final Map<String, String> data) { 
    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
    final Intent notificationIntent = new Intent(getApplicationContext(), SplashActivity.class); 
    PendingIntent pi = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 
     // The user-visible name of the channel. 
     CharSequence name = "Name"; 
     // The user-visible description of the channel. 
     String description = "Description"; 
     int importance = NotificationManager.IMPORTANCE_HIGH; 
     NotificationChannel mChannel = new NotificationChannel(DEFAULT_CHANNEL_ID, name, importance); 
     // Configure the notification channel. 
     mChannel.setDescription(description); 
     mChannel.enableLights(true); 
     // Sets the notification light color for notifications posted to this 
     // channel, if the device supports this feature. 
     mChannel.setLightColor(Color.RED); 
     mChannel.enableVibration(true); 
     mChannel.setVibrationPattern(NOTIFICATION_VIBRATION_PATTERN); 
     mNotificationManager.createNotificationChannel(mChannel); 
    } 


    Notification mNotification = new NotificationCompat.Builder(this, DEFAULT_CHANNEL_ID) 
      .setStyle(new NotificationCompat.BigTextStyle().bigText(data.get(AppConstant.MESSAGE))) 
      .setSmallIcon(R.mipmap.ic_launcher) 
      .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)) 
      .setContentTitle("App name") 
      .setContentText(data.get(AppConstant.MESSAGE)) 
      .setContentIntent(pi) 
      .setDefaults(Notification.DEFAULT_ALL) 
      .setPriority(Notification.PRIORITY_MAX) 
      .setAutoCancel(true) 
      .setChannelId(DEFAULT_CHANNEL_ID) 
      .build(); 
    mNotificationManager.notify(0, mNotification); 
} 
0

아래의 메소드를 확인하십시오. 작동에 문제가 없습니다. 알림 서버에서 json 데이터를 가져옵니다.

public class MyFirebaseMessagingService extends FirebaseMessagingService { 

    private static final String TAG = "MyFirebaseMsgService"; 

    @Override 
    public void onMessageReceived(RemoteMessage remoteMessage) { 

     AppLog.Log(TAG, "From: " + remoteMessage.getFrom()); 
     JSONObject json = null; 

     if (remoteMessage.getData().size() > 0) { 
      Log.v(TAG, "Message data " + remoteMessage.getData()); 

      json = new JSONObject(remoteMessage.getData()); 
      AppLog.Log(TAG, "Json object " + json); 

     } 

     if (json != null) { 

      try { 
       int icon = R.mipmap.ic_launcher; 
       int mNotificationId = 001; 
       // MainDrawerActivity is the class which open on the click of notification in status bar 
       Intent intent = new Intent(this, MainDrawerActivity.class); 
       intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); 

       //FLAG_UPDATE_CURRENT is important 
       PendingIntent pendingIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT); 


       NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
         this); 
       Notification notification = mBuilder.setSmallIcon(icon).setTicker("your title").setWhen(0) 
         .setAutoCancel(true) 
         .setContentTitle("your title") 
         .setStyle(new NotificationCompat.BigTextStyle().bigText("message")) 
         .setContentIntent(pendingIntent) 
         .setContentText("message").build(); 

       NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); 
       notificationManager.notify(mNotificationId, notification); 

      } catch (Exception e) { 
       e.printStackTrace(); 
      } 

     } 
    } 
}