I have a sharedPreference that that gets updated continuously (around every second)from a Class which extends BroadcastReceiver.
The first few times, the registerOnSharedPreferenceChangeListener gets called, but after a while, it stops getting called(I dont even press any button on my emulator).
I know that the sharedPreference is still getting updated because I have seen my log. It is a problem with the registerOnSharedPreferenceChangeListener.
This is the code for the listener(using the suggestion from here)
My shared preference is getting updated almost once every second.
Here is the code for my listener:
SharedPreferences.OnSharedPreferenceChangeListener listener=new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
if(key=="TIME")
{
Log.v("Tagger","Value has changed");
long L=-2;
if(sharedPreferences.contains("TIME"))
{
L=sharedPreferences.getLong("TIME", 0);
long HH=(L/1000)/3600;
long MM=((L/1000)/60)%60;
long SS=(L/1000)%60;
MILLIS-=1000;
mainHH.setText(Long.toString(HH));
mainMM.setText(Long.toString(MM));
mainSS.setText(Long.toString(SS));
}
if(L<=0)
{
Editor edit=sharedPreferences.edit();
edit.remove("TIME");
edit.commit();
Log.v("VALUE",Long.toString(454L));
Intent intent = new Intent(getApplicationContext(), TimerAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
TimerAlarmReceiver.alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
TimerAlarmReceiver.alarmMgr.cancel(pendingIntent);
start.setText("Start the Test?");
TimerOn=false;
edit.putBoolean("TimerOn", TimerOn);
edit.commit();
}
}
}};
sharedPreferences.registerOnSharedPreferenceChangeListener(listener);
I have provided the full code because something else might be the problem.
EDIT:: here is my BroadcastReceiver class
public class TimerAlarmReceiver extends BroadcastReceiver {
public static long TIME;
public static Boolean TimerOn=false;
public static AlarmManager alarmMgr ;
@Override
public void onReceive(Context context, Intent intent) {
//Toast.makeText(context, "Alarm went off", Toast.LENGTH_SHORT).show();
/* SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
Editor editor = sharedPreferences.edit();
editor.putLong(key, value);
editor.commit();*/
SharedPreferences time = PreferenceManager
.getDefaultSharedPreferences(context);
long T = time.getLong("TIME",594554L);
Editor editor=time.edit();
editor.putLong("TIME", T-1000);
editor.commit();
Log.v("Tag", Long.toString(T));
//this gets updated and i can see the new values of T
}
public static void setTime(long T)
{
TIME=TimerActivity.DMILLIS;
}
}
OnSharedPreferenceChangeListener
s are registered via weak reference. Make sure you keep a reference to the listener by setting it to an instance variable.