设备未接收到 Firebase 云消息通知

我有一个与 FireBase 云消息的问题,其中我得到的令牌从设备和发送通知测试通过谷歌 FireBase 通知控制台,但是,通知从来没有记录或推送到安卓虚拟设备。FCM 的文档几乎完全就是我在下面提到的代码,除此之外没有什么别的东西可以让你使用 firebase 来获得推送通知。我已经通过了所有的设置信息(build.gradle 添加,安装谷歌播放服务,等等..。.)但仍然没有生成消息。我确实收到一个一次性的错误后立即推送通知说: “ I/FA: 标签管理器没有找到,因此将不会使用”,但这是唯一的数据输出,我没有发现任何有关标签管理器的要求和 FCM 在谷歌。我没有收到日志猫或设备的推送通知的代码出了什么问题?请让我知道任何进一步的信息,将有助于。 谢谢。

通知 Genie.java

public class NotificationGenie extends FirebaseMessagingService {


private static final String TAG = "Firebase_MSG";


@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO(developer): Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// 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.
sendNotification(remoteMessage.getNotification().getBody());
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
}


private void sendNotification(String messageBody) {
Intent intent = new Intent(this, PostLoginActivity.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.tf2spyprofile)
.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());
}


}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.test.movile_android">


<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />


<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".LoginActivity"
android:label="@string/title_activity_login">
<intent-filter>
<action android:name="android.intent.action.MAIN" />


<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DashBoardActivity"
android:label="@string/title_activity_dash_board"
android:theme="@style/AppTheme.NoActionBar">
</activity>


<activity
android:name=".NewOrderActivity"
android:label="@string/title_activity_dash_board"
android:theme="@style/AppTheme.NoActionBar">
</activity>


<activity
android:name=".PostLoginActivity"
android:label="@string/title_activity_dash_board"
android:theme="@style/AppTheme.NoActionBar">
</activity>
</application>


<service
android:name=".NotificationGenie">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>

189499 次浏览

You have placed your service outside the application tag. Change bottom to this.

<service
android:name=".NotificationGenie">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>


</application>

I faced the same issue of Firebase cloud messaging not received by device.

In my case package name defined on Firebase Console Project was diferent than that the one defined on Manifest & Gradle of my Android Project.

As a result I received token correctly but no messages at all.

To sumarize, it's mandatory that Firebase Console package name and Manifest & Gradle matchs.

You must also keep in mind that to receive Messages sent from Firebase Console, App must be in background, not started neither hidden.

I had a similar problem, but in my case I was missing the google-services plugin from my Gradle build (I was adding Firebase to an existing project).

I added the following to my root build.gradle:

classpath 'com.google.gms:google-services:3.1.0'

and the following to the end of my app-level build.gradle:

apply plugin: 'com.google.gms.google-services'

I then had to download the google-services.json file from the Firebase Console (having originally imported an existing Google Cloud project) and copy it to my app directory`.

I faced the same problem but I had still had some debris in my manifest from the old GCM. When I took the following permission out of my manifest it fixed the error. com.google.android.c2dm.permission.RECEIVE

I had the same problem and it is solved by defining enabled, exported to true in my service

  <service
android:name=".MyFirebaseMessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>

"You must also keep in mind that to receive Messages sent from Firebase Console, App must be in background, not started neither hidden." --- According to @Laurent Russier's comment.

I never got any message from Firebase, until i put my app in the background.

This is true only on usb connection for emulator you get notification in foreground as well

You need to Follow Below Manifest Code (must have Service in manifest)

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="soapusingretrofitvolley.firebase">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />


<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>


<service
android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>


<service
android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
</application>


</manifest>

Call super.OnMessageReceived() in the Overriden method. This worked for me! Finally!

private void sendNotification(String message) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
int requestCode = 0;
PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_ONE_SHOT);
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.URI_COLUMN_INDEX);
NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(message)
.setColor(getResources().getColor(R.color.colorPrimaryDark))
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("FCM Message")
.setContentText("hello").setLargeIcon(((BitmapDrawable) getResources().getDrawable(R.drawable.dog)).getBitmap())
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(((BitmapDrawable) getResources().getDrawable(R.drawable.dog)).getBitmap()))
.setAutoCancel(true)
.setSound(sound)
.setContentIntent(pendingIntent);


NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, noBuilder.build());

If you have just added FCM to an existing app, onTokenRefresh() will NOT be called. I got it to run by uninstalling the app and installing it again.

maybe it is from the connection I changed the connection from Ethernet to wireless the it worked without doing anything else

When you copying your device token, it might copying the space, double check you have copied the correct token

    <activity android:name=".activity.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />


<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Firebase Notifications -->
<service android:name=".service.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>


<service android:name=".service.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>

I've been working through this entire post and others as well as tutorial videos without being able to solve my problem of not receiving messages, the registration token however worked.

Until then I had only been testing the app on the emulator. After trying it on a physical phone it instantly worked without any prior changes to the project.

I had this problem, I checked my code. I tried to fix everything that was mentioned here. lastly the problem was so stupid. My device's Sync was off. that was the only reason I wasn't receiving notifications as expected.

enter image description here

As if you want your app to run in > 24 versions too, follow these:

1.Add this in your strings.xml

< string name="default_notification_channel_id" translatable="false"> fcm_default_channel

  1. Add this meta-data in your manifest file:

< meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="@string/default_notification_channel_id" />

3.for creating notifications (with images) use this method where you are handling notifications, if directly then add in the firebasemessaging service or if you are using some util class then add in that util class :

   @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public static void createBigNotification(Bitmap bitmap, int icon, String message, Uri alarmSound) {
final int NOTIFY_ID = 0; // ID of notification
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(NOTIFICATION_SERVICE);
String id = mContext.getString(R.string.default_notification_channel_id); // default_channel_id
String title = mContext.getString(R.string.app_name);
Intent intent;
NotificationCompat.Builder builder;
if (notificationManager == null) {
notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
}
PendingIntent resultPendingIntent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = notificationManager.getNotificationChannel(id);
if (mChannel == null) {
mChannel = new NotificationChannel(id, title, importance);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notificationManager.createNotificationChannel(mChannel);
}
builder = new NotificationCompat.Builder(mContext, id);
intent = new Intent(mContext, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
resultPendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
bigPictureStyle.setBigContentTitle(title);
bigPictureStyle.setSummaryText(Html.fromHtml(message).toString());
bigPictureStyle.bigPicture(bitmap);


builder.setContentTitle(title)        // required
.setSmallIcon(R.drawable.app_icon)   // required
.setContentText(message) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setSound(alarmSound)
.setStyle(bigPictureStyle)
.setContentIntent(resultPendingIntent)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
.setTicker(title)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
} else {
builder = new NotificationCompat.Builder(mContext, id);
intent = new Intent(mContext, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
resultPendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
bigPictureStyle.setBigContentTitle(title);
bigPictureStyle.setSummaryText(Html.fromHtml(message).toString());
bigPictureStyle.bigPicture(bitmap);


builder.setContentTitle(title)     // required
.setSmallIcon(R.drawable.app_icon)   // required
.setContentText(message) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setSound(alarmSound)
.setStyle(bigPictureStyle)
.setContentIntent(resultPendingIntent)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
.setTicker(title)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setPriority(Notification.PRIORITY_HIGH);
}
Notification notification = builder.build();
notificationManager.notify(NOTIFY_ID, notification);
}

Follow these steps and your notification will come in the notification tray.

In my case, I noticed mergedmanifest was missing the receiver. So I had to include:

 <receiver
android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</receiver>

In my case, I manually killed some google play services and forgot about it.

Later, I have to restart the device, after that I can receive notification without any problem.

In my case, I just turned on WiFi and mobile data in the emulator and it worked like a charm.

After spending hours on this issue I finally realised the problem when I intentionally corrupted the format of the "google-services.json" and my build still succeeded. My IDE(AndroidStudio) does not notice the changes in this file. I tried many things, "reload from disk", gradle task "cleanBuildCache", new virtual device, uninstalling/reinstalling the app etc but none worked.

For me the solution was in AndroidStudio -> Build -> Clean Project and Build -> Rebuild Project

PS: Also make sure "google-services.json" is in the "app" folder.

I followed all the steps according to the firebase website to set up sending notifications for Android APPs. I tried many times but I can't received the notifications no matter on virtue device or physical device. After I changed some settings(those settings about receiving notifications in the SETTING section ) in virtue device and physical device, both virtual and physical devices started receiving notifications.

2 mistakes that I had to correct, after which the issue was resolved.

Referring to the official documentation gave this nice snippet which helped confirm the Subscription status.

 Firebase.messaging.subscribeToTopic(TOPIC)
.addOnCompleteListener { task ->
var topicSubscriptionStatus = "Subscribed"
if (!task.isSuccessful) {
topicSubscriptionStatus = "Subscribe failed"
}
Log.d(TAG, topicSubscriptionStatus)
Toast.makeText(baseContext, topicSubscriptionStatus, Toast.LENGTH_SHORT).show()
}
  1. my topic name had a typo "/topic/" instead of the correct one "/topics/". Right after correcting this the service started receiving the messages

  2. I had to add the flag "FLAG_IMMUTABLE" on the PendingIntent (error in logcat mentioned this is needed from S)

(I m on Tiramisu)