invalidateOptionsMenu() 不工作

invalidateOptionsMenu() not working

每次从一个信号通知 class 收到新通知时,我想在我的 android 应用程序上更新通知计数标记。流程是,只要收到新通知,我就会将计数保存到 sharedpreference。它已经完成并且每次收到通知时,计数徽章都会更新,问题是更新工具栏中的图标正在使用无效选项菜单。 所以我在我的 MainActivity class

中创建了这个方法
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 通知中调用它 class 如下所示

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

下面是我的通知计数徽章

如何解决这个问题?

按照这些步骤从通知更新。

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