我想在每次从一个信号通知类收到新通知时更新我的android应用程序上的通知计数徽章。流程是,每当收到新通知时,我都会将计数保存到sharedpreference。它已经完成并且每次收到通知时,计数徽章都会更新,问题是使用无效选项菜单更新工具栏中的图标。 所以我在MainActivity类中创建了此方法
public void updateNotif(){
HashMap<String, Integer> notif = notif_count.getCount();
count = notif.get(NotifCountSession.KEY_COUNT);
Log.e(MainActivity.class.getSimpleName(), "COUNT : "+count);
invalidateOptionsMenu();
}
然后在如下所示的OneSignal通知类中调用它
public class Notification implements OneSignal.NotificationReceivedHandler {
private NotifCountSession session;
private Application app;
private int count;
public Notification(Application app){
this.app = app;
}
@Override
public void notificationReceived(OSNotification notification) {
init();
count++;
session.saveCount(count);
//this code works
Log.e(MainActivity.class.getSimpleName(), "COUNT NOTIF : "+count);
//but this one not
new MainActivity().updateNotif();
}
private void init(){
session = new NotifCountSession(app);
HashMap<String, Integer> notif = session.getCount();
count = notif.get(session.KEY_COUNT);
}
}
如何解决这个问题?
答案 0 :(得分:1)
请按照以下步骤从通知中进行更新。
1)添加您的MainActivity
private BroadcastReceiver mMyBroadcastReceiver;
然后,
2)在onResume
@Override
protected void onResume() {
super.onResume();
mMyBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateNotif();
}
};
try {
LocalBroadcastManager.getInstance(this).registerReceiver(mMyBroadcastReceiver, new IntentFilter("your_action"));
} catch (Exception e) {
e.printStackTrace();
}
}
//和您的其他代码
3)然后在onPause中注销
@Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMyBroadcastReceiver);
}
4)最后,在您的notificationReceived
方法中
Intent intent = new Intent("your_action");
LocalBroadcastManager localBroadcastManager =LocalBroadcastManager.getInstance(this);
localBroadcastManager.sendBroadcast(intent);