Reputation: 127
I want to update my UI as soon as I receive the push notification, similarly how facebook updates its notification count.
What I have achieved:
Problem:
I am in the activity (UI) and the notifications keep on coming, thus changing the value in the shared preferences. Now my UI is not updated until I move to another activity and come back. UI is created in onCreate method.
Question: How can I update my UI continuously as soon as the notification arrives, without moving away from or changing my current activity (UI).
Thanks
Upvotes: 1
Views: 1759
Reputation: 3776
You could register your activity to the same broadcast as the class you have right now, using sendOrderedBroadcast
you can specify the order your receivers will get the broadcasted message. Here you can put your Activity with a higher priority than the other class and
A) Update your shared preferences B) update your textview
and then call to abortBroadcast, I'll give you a sample code:
The class that sends the broadcast:
Intent intent = new Intent();
intent.setAction("increase action");
intent.putExtra("new value");
context.sendOrderedBroadcast(intent,null);
Your activity
First you have to create a broadcastreceiver
private class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//Do your work
abortBroadcast();
}
}
And then register it
IntentFilter filterSync = new IntentFilter();
filterSync.addAction("increase action");
filterSync.setPriority(100);
registerReceiver(myregister, filterSync);
Remember this, you have to register your BroadcastReceiver
in your onResume
method and unregister it in your onPause
method.
Hope it helps
Upvotes: 1
Reputation: 16414
While your method of storing the data is questionable, you can register an OnSharedPreferenceChangeListener
. This will receive a callback when your preferences are changed. Note that it must be an instance variable and not an inner anonymous class.
private OnSharedPreferenceChangeListener preferenceChangeListener = new OnSharedPreferenceChangeListener() {
@Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
updateNotificationCount();
}
};
You can register this as follows (assuming you're just using the default shared prefs file):
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPrefs(context);
sharedPrefs.registerOnSharedPreferenceChangeListener(preferenceChangeListener);
Upvotes: 1
Reputation: 31
If you store a value in a shared preference than I suggest using OnSharedPreferenceChangeListener http://developer.android.com/reference/android/content/SharedPreferences.OnSharedPreferenceChangeListener.html in the activity.
Upvotes: 3