我正在设置Firebase推送通知,并且根据文档,我做了我猜得到的一切
所以我所做的是从“工具”>“ Firebase”>“云消息传递”中添加的依赖项,看到我的收获
implementation 'com.google.firebase:firebase-core:11.8.0'
implementation 'com.google.firebase:firebase-messaging:11.8.0'
implementation 'com.google.android.gms:play-services-ads:11.8.0'
此后,我创建了一个MyyFirebaseMessagingService类并扩展了FirebaseMessagingService,请参见下文
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d("RefreshedToken", "onMessageReceived: " + remoteMessage.getNotification().getBody());
showNotification(remoteMessage.getNotification().getBody());
}
private void showNotification(String message) {
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.drawable.logo)
.setContentTitle("Quotes App")
.setContentText(message)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, notification);
}}
此后,我在清单中添加了服务
<service
android:name=".MyFirebaseMessagingService"
android:enabled="true"
android:exported="true"
>
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
现在,当我尝试发送通知时,我没有收到通知。我在做什么错
答案 0 :(得分:2)
创建频道并设置重要性
在可以在Android 8.0及更高版本上发布通知之前,您必须 必须通过以下方式在系统中注册您的应用的通知频道 将NotificationChannel的实例传递给 createNotificationChannel()。
正如documentation所说,您需要在android 8及更高版本中添加一个通知通道,以便系统显示您的通知。
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
答案 1 :(得分:1)
首先,您需要创建通知频道...并且频道ID应该在1到10之间。
其次,升级到app / gradle.build
如果应用位于前台(用户可见),则会调用onMessageReceived()
。
如果应用程序在后台(用户不可见),则不会调用onMessageReceived()
并且通知会自动显示给用户,而无需您手动显示它们...并且数据值是在点击时作为意图的额外内容传递给您的启动器活动。