【问题标题】:invalidateOptionsMenu() not workinginvalidateOptionsMenu()不起作用
【发布时间】:2018-08-13 08:09:03
【问题描述】:

每次从一个信号通知类收到新通知时,我想更新我的 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);
}
}

下面是我的通知计数徽章

如何解决这个问题?

【问题讨论】:

  • 这条线new MainActivity().updateNotif()是一场灾难。永远不要创建 Activity 的实例。它是一个由系统自身实例化的组件。
  • 那么如何让它工作呢?
  • 我建议你首先阅读Activity。它是 android 的骨干。要使其工作,您可以广播消息或调用静态方法。

标签: android notifications onesignal


【解决方案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);

【讨论】:

  • 欢迎兄弟。祝你好运。
猜你喜欢
  • 2014-10-02
  • 2015-12-04
  • 2013-01-31
  • 2019-11-08
  • 2015-07-17
  • 2015-03-15
  • 2012-12-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多