我想在工具栏图标上设置通知计数标志。我使用onesignal来获取实时通知。因此,每次收到新通知时,我都会将计数保存到sharedPreference并将其显示在工具栏图标上,如下图
如何实现?
所以这里的主要问题是如何处理从一个信号接收到的通知?
这是我的notif count sharedpreference类
public class NotifCountSession {
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
SharedPreferences.Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpreference file name
private static final String PREF_NAME = "notif";
// User name (make variable public to access from outside)
public static final String KEY_COUNT = "count";
// Constructor
public NotifCountSession(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void saveCount(int count){
// Storing value in pref
editor.putInt(KEY_COUNT, count);
editor.commit();
}
public HashMap<String, Integer> getCount(){
HashMap<String, Integer> notif = new HashMap<>();
// user name
notif.put(KEY_COUNT, pref.getInt(KEY_COUNT, 0));
return notif;
}
public void resetCount(){
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
}
}
答案 0 :(得分:2)
请尝试以下解决方案:
通过上下文初始化有关您活动的一种信号:
OneSignal.startInit(this)
.setNotificationReceivedHandler(new ExampleNotificationReceivedHandler(this))
.init();
现在,您可以在onesignal类上使用上下文了:
private Application application;
public ExampleNotificationReceivedHandler(Application application) {
this.application = application; //Done now you have a context
}
答案 1 :(得分:0)
根据OneSignal Documentation在您的OneSignal.NotificationReceivedHandler
类中实现Notification
然后使用setNotificationReceivedHandler(new NotifCountSession(this))
方法(通常是Application类)在其中初始化OneSignal
实例,如下所示:
OneSignal.startInit(this)
.setNotificationReceivedHandler(new NotifCountSession(this))
.init();