gpt4 book ai didi

java - 如何计算 Android 中收到的通知并设置图标徽章

转载 作者:行者123 更新时间:2023-11-29 02:31:19 24 4
gpt4 key购买 nike

我正在开发一个在通知栏中接收通知的应用程序,但我想计算通知数量并设置徽章图标通知数量,我正在使用库 ShortcutBadge,但图标应用程序上只显示 1 个数字。如何计算收到的通知和在图标应用上设置计数通知。

import java.util.ArrayList;
import java.util.List;

import me.leolin.shortcutbadger.ShortcutBadger;

import static android.content.Context.MODE_PRIVATE;


public final class NotificationMaker {


private NotificationMaker() throws InstantiationException {
throw new InstantiationException("This class is not created for instantiation");
}

@SuppressLint("RestrictedApi")
public static void showNotification(Context context, User user, String fromName, String subject) {



Settings settings = new Settings(context);


NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);

mBuilder.setSmallIcon(R.drawable.notification);
mBuilder.setTicker(context.getString(R.string.notification_ticker_new_email));

mBuilder.setContentTitle(fromName + " to " + user.getUsername());

mBuilder.setContentText(subject);
mBuilder.setSound(Uri.parse(settings.getString(Settings.KEY_NOTIFICATION_SOUND)));
mBuilder.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
mBuilder.setAutoCancel(true);

Intent notificationIntent = new Intent(context, LoginActivity.class);

TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(LoginActivity.class);

stackBuilder.addNextIntent(notificationIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
int count=1;
ShortcutBadger.applyCount(context,count);



NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

mNotificationManager.notify((int) (System.currentTimeMillis()), mBuilder.build());

CurrentUser.setCurrentUser(user, context);


}

最佳答案

计数大小需要自己实现。您可以使用共享首选项。例如,您需要使用如下内容从您的 SharedPreferences 中读取先前的计数:

// You need to use this import
//import android.preference.PreferenceManager;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

// Read previous value. If not found, use 0 as default value.
int count = prefs.getInt("count_key", 0);

// because you need to show the badge again, it means you need
// to increment the count
count = count + 1;

// Then apply it
ShortcutBadger.applyCount(context, count);

// After that, you need to save the value again for another badge count
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("count_key", count);
editor.commit();

关于java - 如何计算 Android 中收到的通知并设置图标徽章,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49513032/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com