0

So I have a broadcast receiver that needs to notify a service that it has received a text message. The only way to do this (as far as I know) is a static method. But the method that is notified need access to the application's preferences.

Every method I have tried says that it cannot be accessed from a static method. So how do I access preferences from a static method?

Andrew Guenther
  • 1,362
  • 2
  • 12
  • 30

2 Answers2

1

You can use the context param of your BroadcastReceiver to get access to stuff that belongs to Context, such as getSharedPreferences

To see some code samples of working with SharedPreferences see this other question Making data persistent in android

Community
  • 1
  • 1
Pentium10
  • 204,586
  • 122
  • 423
  • 502
1

The only way to do this (as far as I know) is a static method.

Hardly. In fact, that approach is not recommended.

If the service is supposed to be in memory when the broadcast is received, have the service register the BroadcastReceiver via registerReceiver() and handle it directly. If the service is not supposed to be in memory when the broadcast is received, use startService() to start the service and send over an Intent (picked up in onStart() of the service).

So how do I access preferences from a static method?

See Pentium10's answer.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Thank you so much, so when I register the receiver, how will I know when something has been received? – Andrew Guenther Aug 21 '10 at 07:17
  • Actually, I have kind of reworked what I am doing, I now have the receiver set to start the service and send over the intent, but I could have multiple text messages come in, so how can I send over another one once the service is already started? (I am still curious as to the answer of the first question) – Andrew Guenther Aug 21 '10 at 07:21
  • @Andrew Guenther: "when I register the receiver, how will I know when something has been received?" -- because the receiver is called with `onReceive()`. Make it be an inner class of the service, and it can call methods on the service. "how can I send over another one once the service is already started?" -- call `startService()` again. Ideally, your service is an `IntentService`, which processes Intents on a background thread, queues up `Intents` if needed, and automatically shuts down when there is no more work to be done. – CommonsWare Aug 21 '10 at 07:56