【发布时间】:2016-09-05 08:26:36
【问题描述】:
我有一个 Android 应用程序,我正在使用某种方法在应用程序图标上显示通知编号。现在我想在收到通知时设置那个数字。
我认为我应该在收到通知时设置数字,所以我将它设置在 onMessageReceived 方法中。但是,我的问题是当我的应用程序在后台时,onMessageReceived 方法未调用,因此未设置通知编号。
以下是我的代码。我在onMessageReceived 中设置了号码。我已经测试了setBadge 方法并且可以验证它是否有效。问题是onMessageReceived没有被调用所以setBadge也没有被调用,它没有设置数字。
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO(developer): Handle FCM messages here.
Log.d(TAG, "From: " + remoteMessage.getFrom());
Conts.notificationCounter ++;
//I am setting in here.
setBadge(getApplicationContext(),Conts.notificationCounter );
Log.e("notificationNUmber",":"+ Conts.notificationCounter);
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
// 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.
}
// [END receive_message]
public static void setBadge(Context context, int count) {
String launcherClassName = getLauncherClassName(context);
if (launcherClassName == null) {
Log.e("classname","null");
return;
}
Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
intent.putExtra("badge_count", count);
intent.putExtra("badge_count_package_name", context.getPackageName());
intent.putExtra("badge_count_class_name", launcherClassName);
context.sendBroadcast(intent);
}
public static String getLauncherClassName(Context context) {
PackageManager pm = context.getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resolveInfos) {
String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
if (pkgName.equalsIgnoreCase(context.getPackageName())) {
String className = resolveInfo.activityInfo.name;
return className;
}
}
return null;
}
当我搜索这个issue 时,我发现如果即将到来的消息是显示消息,那么只有当应用程序处于前台时才会调用onMessageReceived。但如果传入消息是数据消息,那么即使应用程序是后台,也会调用onMessageReceived。
但是我的朋友告诉我谁在发送通知(服务器端),消息已经作为显示和数据消息发送。他说数据对象被填充了。
以下是即将到来的消息的JSON,它有数据对象。
{
"to":"my_device_id",
"priority":"high",
"notification":{
"body":"Notification Body",
"title":"Notification Title",
"icon":"myicon",
"sound":"default"
},
"data":{
"Nick":"DataNick",
"Room":"DataRoom"
}
}
如果我只使用数据对象,则按他们所说的那样调用 onMessageReceived,但该时间通知不会出现在顶部。
如果消息也是数据消息,为什么不调用onMessageReceived。我应该做一些不同的事情来处理数据消息吗?它是否与客户端的显示消息相同。
任何帮助将不胜感激。提前致谢。
【问题讨论】:
标签: android google-cloud-messaging firebase-cloud-messaging firebase-notifications