You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase通知正常显示但点击无法打开应用,求助排查解决

Firebase通知点击无法打开应用的问题

我在应用中集成了Firebase Notification,目前能正常接收并显示通知,但点击通知时无法打开应用。以下是我的MyFirebaseMessagingService类实现:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    Intent intent ;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        String body = "";
        String title = "";
        String type = "";
        String json_Data = "";
        String referenceId = "";

        Log.d("FirebaseMsgService", "Message received: " + remoteMessage);

        try {

            if (remoteMessage.getNotification() != null) {

                body = Objects.requireNonNull(remoteMessage.getNotification()).getBody();
                title = remoteMessage.getNotification().getTitle();
                type = remoteMessage.getNotification().getClickAction();
               /* body = remoteMessage.getNotification().getBody();
                title = remoteMessage.getNotification().getTitle();*/

                Log.d("FirebaseMsgService", "Notification received - Title: " + title + ", Body: " + body + ", Type: " + type);

            }

            referenceId =   remoteMessage.getData().get("refrence_id");
         //   type = remoteMessage.getData().get("click_action"); // Get the click_action

            Log.d("FirebaseMsgService", "Reference ID: " + referenceId);


        }catch (Exception e){
            type ="";
            Log.d("FirebaseMsgService", "" + e.toString());
            Log.d("FirebaseMsgService",e.toString() + "" +e.getMessage().toString());
        }

        sendNotification(body , title , type , referenceId);

    }

    private void sendNotification(String body , String title , String noti_type , String postId) {

        Log.d("FirebaseMsgService", "Intent Data: noti_type=" + noti_type + ", postId=" + postId);


        if(noti_type.equals("disscussion_board")){
            intent = new Intent(getApplicationContext(), DetailDiscussionActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("borad_id" , postId);
            intent.putExtra( "sss" ,bundle);
        } else if(noti_type.equals("sell_vehicle")){
            intent = new Intent(getApplicationContext(), CarListForSaleActivty.class);
            Bundle bundle = new Bundle();
            bundle.putString("sell_id" , postId);
            bundle.putString("title" , title);
            intent.putExtra( "sss" ,bundle);
        } else if (noti_type.equals("portable_charger_booking")) {
            intent = new Intent(getApplicationContext(), PortableChargerBookingHistoryDetailsActivity.class);
            intent.putExtra("booking_id" , postId);
            intent.putExtra("title" , title);
           // intent.putExtra( "sss" ,bundle);

        } else if (noti_type.equals("charging_service")) {
            intent = new Intent(getApplicationContext(), ChargingServiceHistoryDetailActivity.class);
            intent.putExtra("service_id" , postId);
            intent.putExtra("title" , title);
            // intent.putExtra( "sss" ,bundle);

        }else if(noti_type.equals("charging_installation_service")){
            intent = new Intent(getApplicationContext(), ChargerInstallationHistoryDetailActivity.class);
            intent.putExtra("requestId" , postId);
            intent.putExtra("title" , title);
        }else {
            intent = new Intent(getApplicationContext(), NotificationListActivity.class);
        }
        int requestCode = (int) System.currentTimeMillis();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), requestCode, intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);

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

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "channelId");

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

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("channelId", getString(R.string.app_name), NotificationManager.IMPORTANCE_DEFAULT);
            channel.setShowBadge(true);
            notificationManager.createNotificationChannel(channel);
            notificationBuilder.setChannelId("channelId");
        }

        Bitmap largeIcon = BitmapFactory.decodeResource(getResources(),
                R.mipmap.ic_launcher);

        notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
        notificationBuilder.setContentTitle(title)
                .setContentText(body)
                .setAutoCancel(true)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(body))
                .setSound(defaultSoundUri)
                .setVibrate(new long[]{1000, 1000})
                .setContentIntent(pendingIntent);


        Random rand = new Random();
        int as = rand.nextInt();
//        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(as /* ID of notification */, notificationBuilder.build());
    }
}

接收通知时无任何日志输出,服务器下发的消息数据如下:

"message": {
    "token": "dSfgsgsfdgsdfgdsfxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "notification": {
      "title": "Completed!",
      "body": "complete body ."
    },
    "data": {
      "title": "Charging Completed!",
      "body": "Charging complete, please lock your EV.",
      "click_action": "portable_charger_booking",
      "refrence_id": "PCB0305"
    },
    "apns": {
      "payload": {
        "aps": {
          "sound": "default"
        }
      }
    },
    "android": {
      "priority": "high",
      "notification": {
        "click_action": "portable_charger_booking"
      }
    }
  }
}

我已在Manifest中配置了intent-filter,期望点击通知时能正常打开应用。


问题排查与修复方案

  • 日志无输出原因:当应用处于后台/杀死状态时,Firebase的通知消息(包含notification字段)会由系统直接处理,不会触发onMessageReceived。只有纯数据消息(仅含data字段)才会在任何状态下触发该方法。

  • 点击无响应的核心修复点:

    1. 修正click_action取值逻辑:优先从data字段获取click_action,兼容后台消息场景:
      // 替换原type赋值逻辑
      type = remoteMessage.getData().get("click_action");
      if (type == null && remoteMessage.getNotification() != null) {
          type = remoteMessage.getNotification().getClickAction();
      }
      
    2. 补充Intent Flag:添加FLAG_ACTIVITY_SINGLE_TOP避免重复创建Activity,同时确保后台能正确拉起:
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
      
    3. 验证Manifest配置:确保目标Activity的Intent Filter包含对应click_action,且Android 12+需设置exported="true":
      <activity
          android:name=".PortableChargerBookingHistoryDetailsActivity"
          android:exported="true">
          <intent-filter>
              <action android:name="portable_charger_booking" />
              <category android:name="android.intent.category.DEFAULT" />
          </intent-filter>
      </activity>
      
    4. 优化通知渠道创建:将通知渠道创建移至Application的onCreate方法,避免重复创建:
      // 在自定义Application类中
      @Override
      public void onCreate() {
          super.onCreate();
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
              NotificationChannel channel = new NotificationChannel("channelId", getString(R.string.app_name), NotificationManager.IMPORTANCE_DEFAULT);
              channel.setShowBadge(true);
              NotificationManager notificationManager = getSystemService(NotificationManager.class);
              notificationManager.createNotificationChannel(channel);
          }
      }
      
    5. 可选:改用纯数据消息:如果需要完全自定义通知逻辑,服务器发送消息时移除notification字段,仅保留data,这样无论应用状态如何,都会触发onMessageReceived。

内容的提问来源于stack exchange,提问作者Sachin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 21:09:51