添加徽章到Android应用程序

时间:2018-03-13 15:02:34

标签: android google-cloud-messaging badge

我在我的应用程序中使用GCM,当我收到通知时,我想要徽章增量中的数字我使用此库  implementation "me.leolin:ShortcutBadger:1.1.21@aar" 在接收中,我在onMessageReceived

中实现了此代码
PendingIntent pendingIntent2 = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);

Uri defaultSoundUri1 = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle(appGCMModel.getGcmTitle())
        .setContentText(appGCMModel.getGcmMessage())
        .setAutoCancel(true)
        .setSound(defaultSoundUri1)
        .setContentIntent(pendingIntent2)
        .setStyle(new NotificationCompat.BigTextStyle()
        .bigText(appGCMModel.getGcmMessage()));

Notification notification = notificationBuilder.build();

ShortcutBadger.applyNotification(getApplicationContext(), notification, i);

NotificationManager notificationManager =
        (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notification);

但是当收到通知时,徽章的数量不会增加 任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

这是因为你没有增加计数。您需要将值保存在 SharedPreferences 中。像这样:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

// get previous count
int count = prefs.getInt("badge_count", 0);
// increment the count
count = count + 1;

// save the new value.
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("badge_count", count);
editor.commit();

// Set to the badge
ShortcutBadger.applyNotification(getApplicationContext(), notification, count);

请不要忘记ShortcutBadger.applyNotification()仅适用于小米设备。阅读更多Xiaomi Device Support