android - FCM 推送通知问题 : When I tap on notification and every time i got getExtras() from intent is null.(应用程序在后台)

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

我收到来自 fcm 的通知。但问题是当我点击通知消息时。它包含消息正文。当我尝试将额外的放入 intent 并尝试从 intent 中获取 getExtras() 时,我总是从 中获取 null > Intent

下面是我的代码。有人可以帮我解决这个问题吗? 提前致谢。

VisuallogyxMessagingService.java

//这是我收到消息的firebase服务。

 public class VisualogyxMessagingService extends FirebaseMessagingService {

        private static final String TAG = VisualogyxMessagingService.class.getSimpleName();

        private NotificationUtils notificationUtils;

        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
            Log.e(TAG, "From: " + remoteMessage.getFrom());
            // Check if message contains a notification payload.
            if (remoteMessage.getNotification() != null) {
                Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
                handleNotification(remoteMessage.getNotification().getBody());
               // this method is called when i tap on notification if notification contains only message.
            }

            // Check if message contains a data payload.
            if (remoteMessage.getData().size() > 0) {
                Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString().replace("\\n", " "));
                HashMap<String, String> hashMap = new HashMap<>(remoteMessage.getData());
                handleDataMessage(hashMap);
  // this method is called when i tap on notification if notification contains only message with data payload.
            }
        }

        private void handleNotification(String message) {
            if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
                // app is in foreground, broadcast the push message
                Intent notificationIntent = new Intent(Config.PUSH_NOTIFICATION);
                notificationIntent.putExtra("message", message);
                LocalBroadcastManager.getInstance(this).sendBroadcast(notificationIntent);
            }
            else{
                // If the app is in background, firebase itself handles the notification
                // app is in background, show the notification in notification tray
                Intent resultIntent = new Intent(getApplicationContext(), DemoActivity.class);
                resultIntent.putExtra("message", message);

                resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

                PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                showNotificationMessage(getApplicationContext(), "Visualogyx App Demo", message, contentIntent);
            }
        }

        private void handleDataMessage(HashMap<String, String> hashMap) {
            Log.e(TAG, "push json: " + hashMap.toString());
            String message = "";
            if (hashMap.containsKey("message"))
                message = hashMap.get("message");
            else if (hashMap.containsKey("default"))
                message = hashMap.get("default");

            Log.e(TAG, "message: " + message);

            if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
                // app is in foreground, broadcast the push message
                Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
                pushNotification.putExtra("json", hashMap);
                LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

            } else {
                // app is in background, show the notification in notification tray
                Intent resultIntent = new Intent(getApplicationContext(), DemoActivity.class);
                resultIntent.putExtra("json", hashMap);

                resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

                PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                showNotificationMessage(getApplicationContext(), "Visualogyx App Demo", message, contentIntent);
            }
        }

        /**
         * Showing notification with text only
         */
        private void showNotificationMessage(Context context, String title, String message, PendingIntent intent) {
            notificationUtils = new NotificationUtils(context);
            notificationUtils.showNotification(title, message, intent);
        }
    }

NotificationUtils.java

public void showNotification(String title, String message,  PendingIntent resultPendingIntent) {
        NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        String NOTIFICATION_CHANNEL_ID = "my_channel_id_visualogyx_023";
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone r = RingtoneManager.getRingtone(mContext, notification);
        r.play();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications",                      NotificationManager.IMPORTANCE_HIGH);

            // Configure the notification channel.
            notificationChannel.setDescription("Channel description");
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
            notificationChannel.enableVibration(true);
            notificationChannel.setImportance(NotificationManager.IMPORTANCE_HIGH);
            notificationChannel.setSound(notification, Notification.AUDIO_ATTRIBUTES_DEFAULT);
            notificationManager.createNotificationChannel(notificationChannel);
        }

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID);

        notificationBuilder.setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSound(notification)
                .setContentIntent(resultPendingIntent)
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(message).setBigContentTitle(title))
                .setTicker("Hearty365")
                .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher_round));

        notificationManager.notify(1337,notificationBuilder.build());
    }

DemoActivity.java

//我尝试从 intent 获取额外内容的 Activity。 onCreate() 方法我试图获取 intent extras

public class DemoActivity extends AppCompatActivity {

    private static final String TAG = DemoActivity.class.getSimpleName();
    private BroadcastReceiver mRegistrationBroadcastReceiver;
    private TextView txtRegId, txtMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo);

        txtRegId = (TextView) findViewById(R.id.txt_reg_id);
        txtMessage = (TextView) findViewById(R.id.txt_push_message);

        mRegistrationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                // checking for type intent filter
                if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) {
                    // gcm successfully registered
                    // now subscribe to `global` topic to receive app wide notifications
                    displayFirebaseRegId();
                } else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
                    // new push notification is received
                    /*HashMap<String ,String> json = (HashMap<String, String>) intent.getSerializableExtra("json");
                    String message = "";
                    String url = "";
                    HashMap<String,String> jsonObject = new HashMap<>(json);
                    message = jsonObject.get("message");
                    if(jsonObject.containsKey("url")){
                        url = jsonObject.get("url");
                        Log.e(TAG, "onReceive url: "+url);
                    }*/
                    String message = intent.getStringExtra("message");
                    Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();

                    txtMessage.setText(message);
                }
            }
        };

        displayFirebaseRegId();

        Intent intent = getIntent();
        String extraAddress = intent.getStringExtra("message");
        Toast.makeText(this, "got message:"+extraAddress, Toast.LENGTH_SHORT).show();
    }



    // Fetches reg id from shared preferences
    // and displays on the screen
    private void displayFirebaseRegId() {
        SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
        String regId = pref.getString("regId", null);

        Log.e(TAG, "Firebase reg id: " + regId);

        if (!TextUtils.isEmpty(regId))
            txtRegId.setText("Firebase Reg Id: " + regId);
        else
            txtRegId.setText("Firebase Reg Id is not received yet!");
    }

    @Override
    protected void onResume() {
        super.onResume();
        // register GCM registration complete receiver
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.REGISTRATION_COMPLETE));

        // register new push message receiver
        // by doing this, the activity will be notified each time a new message arrives
        LocalBroadcastManager.getInstance(this).
                registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.PUSH_NOTIFICATION));
        // clear the notification area when the app is opened
        NotificationUtils.clearNotifications(getApplicationContext());
    }

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
        super.onPause();
    }
}

当我点击通知时,我总是从 intent 得到 null。 谢谢。

最佳答案

VisualogyxMessagingService.java 你先检查 if (remoteMessage.getNotification() != null)并通过 handleNotification(remoteMessage.getNotification().getBody()); 发送通知在这种情况下,将 resultIntent.putExtra("message", message);进入你的Intent然后将其发射到 DemoActivity.java .

但是,你不return紧接着,导致您的代码继续检查 if (remoteMessage.getData().size() > 0) ,它还会发送另一个 Intent resultIntent.putExtra("json", hashMap); , 与 "json"字段,它将取代您之前发送的通知(因为它是相同的通知 channel 和 ID)。因此,这个新的 Intent只有一个 "json"字段而不是 "message" field 。要解决此问题,请尝试放置 return第一个之后if像这样检查:

@Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.e(TAG, "From: " + remoteMessage.getFrom());
        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
            handleNotification(remoteMessage.getNotification().getBody());
            return;
           // this method is called when i tap on notification if notification contains only message.
        }

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString().replace("\\n", " "));
            HashMap<String, String> hashMap = new HashMap<>(remoteMessage.getData());
            handleDataMessage(hashMap);
        }
    }

在你的DemoActivity.java

Intent intent = getIntent();
HashMap<String, String> jsonData = intent.getSerializableExtra("json");
String message = intent.getStringExtra("message");

关于android - FCM 推送通知问题 : When I tap on notification and every time i got getExtras() from intent is null.(应用程序在后台),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50869975/

相关文章:

android - 在 WebView 中播放 .mp4

android - 隐藏安卓小部件

android - ViewPager Activity 通知特定事件的 Fragment

ios - iOS 7和iOS 8的 Urban Airship 故障

java - 如何在 Android 中将 Image 转换为 byte[]

javascript - 我正在尝试从函数内提取 doc.data 数组并在范围之外使用它

javascript - 为什么 Firebase `accessToken` 位于如此奇怪的标题下?

android - Firebase Auth - 使用电子邮件和密码 - 检查用户是否已注册

php - 未收到来自 Amazon SNS 的 GCM 推送通知

ios - 使用 Swift 的 Firebase 推送通知在 ios 11.4 中不起作用