开发者

Keeping count of notifications in a broadcast receiver

开发者 https://www.devze.com 2023-02-11 13:12 出处:网络
I am trying to keep a count going on the number of unread notifications in a broadcast receiver and have the number of unread notifications display differently as they accumulate but every time the re

I am trying to keep a count going on the number of unread notifications in a broadcast receiver and have the number of unread notifications display differently as they accumulate but every time the receiver is fired its going to re-initialize everything and clear out the count. How can i keep control of the count, am i going to have to create an开发者_如何学Cother class just to keep the variables? that seems like a lot of work for just something so simple


If you're just looking to persist a value between instantiations of your BroadcastReceiver, store the result in a private Preferences object. You can read the stored value in at the beginning of each onReceive(), and the write it back out at the end. Something like:

public static final String PREFS_NAME = "com.examples.myapplication.PREFS";
public static final String KEY_COUNT = "notificationCount";

private int currentCount;

public void onReceive(Context context, Intent intent) {
    SharedPreferences values = context.getSharedPreferences(PREFS_NAME, Activity.MODE_PRIVATE);
    currentCount = values.getInt(KEY_COUNT, 0);  //Sets to zero if not in prefs yet

    //Do your magic work here

    //Write the value back to storage for later use
    SharedPreferences.Editor editor = values.edit();
    editor.put(KEY_COUNT,currentCount);
    editor.commit();
}

You could also write to the global standard preferences with PreferenceManager.getDefaultSharedPreferences(context) instead, which wouldn't require you to define a name.

0

精彩评论

暂无评论...
验证码 换一张
取 消