如何处理收到的 oneSignal 通知

How to handle oneSignal notification received

我想在工具栏图标上制作通知计数标记。我使用 onesignal 获得实时通知。所以每次有新通知时,我都会将计数保存到 sharedPreference 并将其显示到工具栏图标,如下图

如何实现?

所以这里的主要问题是如何处理从一个信号收到的通知?

这是我的通知计数共享偏好 class

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();
}
}

根据 OneSignal Documentation 在您的 Notification class

中实施 OneSignal.NotificationReceivedHandler

然后使用 setNotificationReceivedHandler(new NotifCountSession(this)) 方法(通常是应用程序 class)初始化 OneSignal 实例,如下所示:

OneSignal.startInit(this)   
   .setNotificationReceivedHandler(new NotifCountSession(this))
   .init();

请尝试以下解决方案:

在你的 activity 上用上下文初始化一个信号:

   OneSignal.startInit(this)   
   .setNotificationReceivedHandler(new ExampleNotificationReceivedHandler(this))
   .init();

现在您可以在信号上使用上下文 class :

 private Application application;

    public ExampleNotificationReceivedHandler(Application application) {
        this.application = application; //Done now you have a context

    }