Android模拟器无法接收FCM推送问题求助
我来帮你梳理下FCM推送收不到的问题,从你的代码和配置来看,有几个关键问题需要调整和检查:
1. 首要问题:Service类名与Manifest配置不匹配
你的代码里定义的服务类是MyFirebaseInstanceService,但在AndroidManifest.xml里注册的却是.services.MyFirebaseMessagingService——这会导致系统找不到处理FCM消息的服务,自然收不到推送!
你需要统一两者的名称:要么把Java类名改成MyFirebaseMessagingService,要么修改Manifest里的服务路径为你的实际类路径(比如如果类没有放在services子包下,就去掉.services前缀)。
修正后的Manifest服务注册示例(假设类名改为MyFirebaseMessagingService且在根包下):
<service android:name=".MyFirebaseMessagingService" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/> </intent-filter> </service>
2. 通知缺少必填的小图标
Android 8.0(API 26)及以上版本要求通知必须设置小图标,否则通知可能无法正常显示。你的NotificationCompat.Builder代码里没有添加.setSmallIcon()方法,这会导致通知被系统拦截。
添加小图标,比如使用应用启动图标:
notificationBuilder.setAutoCancel(true) .setDefaults(Notification.DEFAULT_ALL) .setWhen(System.currentTimeMillis()) .setSmallIcon(R.mipmap.ic_launcher) // 新增这行 .setContentTitle(title) .setContentText(body) .setContentInfo("Info");
3. 通知渠道优化:避免重复创建+提高重要性
你现在每次收到消息都会创建通知渠道,这是不必要的,而且IMPORTANCE_DEFAULT在部分机型上可能不会弹出前台通知。建议先检查渠道是否存在,再创建,同时把重要性设为IMPORTANCE_HIGH确保通知能弹出:
修改showNotification方法里的渠道创建逻辑:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // 先检查渠道是否已存在 if (notificationManager.getNotificationChannel(NOTIFICATION_CHANNEL_ID) == null) { NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID, "Notification", NotificationManager.IMPORTANCE_HIGH // 修改为HIGH ); notificationChannel.setDescription("Team Tarang"); notificationChannel.enableLights(true); notificationChannel.setLightColor(Color.BLUE); notificationChannel.enableVibration(true); // 可以添加上震动 notificationManager.createNotificationChannel(notificationChannel); } }
4. 区分FCM的两种消息类型
FCM推送分两种类型,接收逻辑不同:
- 通知消息(notification字段):当应用在后台时,系统会直接显示通知,不会走
onMessageReceived;只有应用在前台时才会触发你的服务方法。 - 数据消息(data字段):无论应用前后台,都会触发
onMessageReceived,需要你自己处理显示通知。
如果你测试用的是通知消息,后台收不到的话可以试试改用数据消息测试,或者检查系统通知权限是否开启。
5. 其他检查项
- 确认
build.gradle(Module level)里添加了FCM依赖:implementation 'com.google.firebase:firebase-messaging:23.4.0' // 使用最新版本 - 确认根目录的
build.gradle里添加了Google服务插件:plugins { id 'com.google.gms.google-services' version '4.3.15' apply false } - 查看
Logcat里的TOKENFIREBASE日志,确认设备已成功获取FCM Token,说明设备和FCM服务器的连接正常。
按照以上步骤调整后,应该就能正常接收FCM推送了!
内容的提问来源于stack exchange,提问作者ahmed mohamady

