【发布时间】:2020-06-22 08:04:36
【问题描述】:
我创建了一个程序,它将在 android 应用程序中添加通知。但不知何故,当应用程序被终止时我无法收到通知
这是我的 FirebaseMessagingService
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
if (remoteMessage.getData() != null)
sendNotification(remoteMessage);
}
private void sendNotification(RemoteMessage remoteMessage){
Map<String, String> map = remoteMessage.getData();
String title = map.get("title");
String content = map.get("content");
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "MyAndroidChannel";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
@SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
"My Notification", NotificationManager.IMPORTANCE_MAX);
notificationChannel.setDescription("This is a sample notification");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0,1000,500,1000});
notificationChannel.enableVibration(true);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
builder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setTicker("Hearty365")
.setContentTitle(title)
.setContentText(content)
.setContentInfo("info");
notificationManager.notify(1,builder.build());
}
}
我添加了一个小图标、标题和内容。另外,我还定义了一个频道 ID。
但我不知道发生了什么...当应用程序运行并处于后台模式时,可以接收通知。但是当应用程序终止时它没有收到。
这是我的 FirebaseMessagingIdService 类
public class FirebaseMessagingIdService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
super.onTokenRefresh();
sendNewTokenServer(FirebaseInstanceId.getInstance().getToken());
}
private void sendNewTokenServer(String token){
Log.d("TOKEN",String.valueOf(token));
}
}
我不认为我做错了什么,但请帮助我。
提前致谢。
【问题讨论】:
-
当应用程序处于活动状态时它可以工作吗?你能显示你的 json 数据吗?
-
是的,它适用于两种情况。背景/前景。这是我的 json:
{ "data": { "title": "Hi", "content": "Hello" }, "to": "api token" }
标签: java android firebase firebase-cloud-messaging