I'm working on a GCM based application where the user can subscribe to several topics.
I need to know which topics the users is subscribed to in two places:
Subscribe
or Unsubscribe
buttons in the UIGcmPubSub
. Basically, if the listener gets a message for the topic which is not in the app's list of topics then probably we have an "obsolete" subscription on the GCM server and have to unsubscribe.So basically I have an activity and a service which both acces some common data and both can modify this data.
I've read that one of the options to share data between an activity and a service is to use shared preferences:
This is suitable for my case as I'd be quite content to share Set<String>
which SharedPreferences
support. Users will be probably interested in just a few topics (say, max. 10).
Here's my code to check if the user is subscribed to a topic:
SharedPreferences preferences = getPreferences(Context.MODE_PRIVATE);
Set<String> subscribedTopics = preferences.getStringSet(AufzugswaechterPreferences.SUBSCRIBED_TOPICS, Collections.<String>emptySet());
boolean subscribedForTopic = subscribedTopics.contains(topic);
Here's the code to modify the subscription (for instance unsubscribe):
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getContext());
Set<String> topics = new TreeSet<String>(preferences.getStringSet(AufzugswaechterPreferences.SUBSCRIBED_TOPICS, Collections.<String>emptySet()));
topics.remove(topic);
preferences.edit().putStringSet(AufzugswaechterPreferences.SUBSCRIBED_TOPICS, topics).apply();
But now I've got my doubts, if it is an appropriate way. I'll be basically accessing shared preferences for every check (in the UI or on received message) as well as on modifications.
Is this the right way to go? Should I share data between the activity and the service directly via preferences or should I somehow cache values?
There is no need for you to cache SharedPreferences
data, as SharedPreferencesImpl already caches the shared data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With