我正在与Firebase一起向用户发送通知。我可以发送基本通知,完全正常。但是,我在将该通知变为抬头通知时遇到了麻烦。我已经尝试过StackOverflow的多种解决方案,但是没有一个与我合作。
下面是我用于接收推送通知的各个类。
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage message) {
super.onMessageReceived(message);
NotificationManager mNotificationManager = getSystemService(NotificationManager.class);
NotificationChannel channel = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
channel = new NotificationChannel("channel",
"Channel description",
NotificationManager.IMPORTANCE_HIGH);
mNotificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getApplicationContext(), "channel")
.setSmallIcon(R.drawable.googleg_standard_color_18)
.setContentTitle(message.getNotification().getTitle())
.setContentText(message.getNotification().getBody())
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(Notification.PRIORITY_HIGH);
mNotificationManager.notify(0, mBuilder.build());
}
}
答案 0 :(得分:1)
您应该像在标准GCM实施中一样添加侦听器服务。 这是tutorial的使用前者,可能对您有用,因为它包括FCM注册以及在Android应用程序步骤中包含该信息
public class MyGcmListenerService extends GcmListenerService {
private static final String TAG = "MyGcmListenerService";
/**
* Called when message is received.
*
* @param from SenderID of the sender.
* @param data Data bundle containing message data as key/value pairs.
* For Set of keys use data.keySet().
*/
// [START receive_message]
@Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);
if (from.startsWith("/topics/")) {
// message received from some topic.
} else {
// normal downstream message.
}
// [START_EXCLUDE]
/**
* Production applications would usually process the message here.
* Eg: - Syncing with server.
* - Store message in local database.
* - Update UI.
*/
/**
* In some cases it may be useful to show a notification indicating to the user
* that a message was received.
*/
sendNotification(message);
// [END_EXCLUDE]
}
// [END receive_message]
运行代码段展开代码段
然后,在AndroidManifest.xml标记中注册您的接收器以侦听传入的通知:
<!-- [START gcm_listener] -->
<service
android:name="gcm.play.android.samples.com.gcmquickstart.MyGcmListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<!-- [END gcm_listener] -->
这种方式-对于应用程序处于前台还是后台的情况,您不必分别处理传入消息。