Andrew Guenther
Andrew Guenther

Reputation: 1492

How to access preferences in a static method

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?

Upvotes: 0

Views: 1087

Answers (2)

CommonsWare
CommonsWare

Reputation: 1007369

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.

Upvotes: 1

Pentium10
Pentium10

Reputation: 207992

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

Upvotes: 1

Related Questions