Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getPreferences(MODE_PRIVATE) is undefined in BroadcastReceiver

Tags:

android

I have application with an activity and a service, I need to save some value in the activity and retrieve in the service.

i could save the value using SharedPreferences in the activity, however, when I try to retrieve the value in the BroadcastReceiver, it says getPreferences is undefined for service.

how could I retrieve my value in BroadcastReceiver?

like image 961
user836026 Avatar asked Dec 26 '22 20:12

user836026


1 Answers

EDITED to reflect change of the original question from Service to BroadcastReceiver.

Instead of using getPreferences(int mode) in the Activity use...

getSharedPreferences(String name, int mode).

The getPreferences(int mode) method is a convenience method for the above and simply passes the Activity class name as the name parameter. This implies it should really only be used for a given Activity to store its own internal preferences and not preferences that need to be global to other app components.

In the case of a BroadcastReceiver the onReceive(...) method is passed a Context parameter so you can use context.getSharePreferences(<some_name>, <mode>) to get the SharedPreferences saved by the Activity.

like image 199
Squonk Avatar answered Mar 23 '23 10:03

Squonk