0

I am working on an android application which can be controlled by other mobile via SMS. I am using PreferenceScreen as layout(settings part of the app). The layout is updated when onResume()is called.

When the command(SMS) is sent via other mobile, service running in the background snoops the incoming sms and change the settings saved in SharedPreferences. In order to see these changes, my Activity need to execute the code in onResume. If I go back to previous activity and come back I can see the changes.

I want to the changes to be displayed as soon the SharedPreferences is changed by running service. What should I do to make it happen?

Sushant Kr
  • 1,953
  • 14
  • 19

1 Answers1

1

Something like this:

public class MyActivity extends Activity implements OnSharedPreferenceChangeListener
{
    public static final String PREFS_NAME = "MyPrefsFile";

    @Override
    protected void onCreate(Bundle state)
    {
      /* get shared preferences */
      SharedPreferences mySharedPreferences = getSharedPreferences(PREFS_NAME, 0);

      /* register listener for changes to the values within the shared preferences */
      mySharedPreferences.registerOnSharedPreferenceChangeListener(this);
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
    {
      /* perform application processing */
      ...

      /* update layout */
      View myView = findViewById(id.my_view);

      /* invalidate the view causing it to be redrawn */
      myView.invalidate();
    }
}
flukey
  • 187
  • 2
  • 8
  • thanku for quick response. This code works if the change is made to the object associated to `mySharedPreferences`. In my service I am creating a new instance of SharedPreferences. So if the changes is made inside service, `onSharedPreferenceChanged` in the current Activity is not called! – Sushant Kr Apr 14 '12 at 01:15
  • Check here: [How to have Android Service communicate with Activity](http://stackoverflow.com/questions/2463175/how-to-have-android-service-communicate-with-activity) – flukey Apr 14 '12 at 02:15
  • I got around with your code but, this was the problem http://stackoverflow.com/questions/10150480/registeronsharedpreferencechangelistener-not-working-for-changes-made-in-differe – Sushant Kr Apr 14 '12 at 02:26