From 8843bcb1ecea5ad0c9fa970faa267ca488de9ad0 Mon Sep 17 00:00:00 2001 From: Zubayer Islam <36497498+zubayer87@users.noreply.github.com> Date: Mon, 23 Dec 2019 21:29:18 -0500 Subject: [PATCH] Fixed sharedpreferences returns garbage after few runs Fixed sharedpreferences returns garbage after few runs. It is also mentioned here: https://developer.android.com/reference/android/content/SharedPreferences "Caution: The preference manager does not currently store a strong reference to the listener. You must store a strong reference to the listener, or it will be susceptible to garbage collection. We recommend you keep a reference to the listener in the instance data of an object that will exist as long as you need the listener." --- .../locationupdatesforegroundservice/MainActivity.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/LocationUpdatesForegroundService/app/src/main/java/com/google/android/gms/location/sample/locationupdatesforegroundservice/MainActivity.java b/LocationUpdatesForegroundService/app/src/main/java/com/google/android/gms/location/sample/locationupdatesforegroundservice/MainActivity.java index 5244c7a7..ab5573af 100644 --- a/LocationUpdatesForegroundService/app/src/main/java/com/google/android/gms/location/sample/locationupdatesforegroundservice/MainActivity.java +++ b/LocationUpdatesForegroundService/app/src/main/java/com/google/android/gms/location/sample/locationupdatesforegroundservice/MainActivity.java @@ -135,8 +135,14 @@ protected void onCreate(Bundle savedInstanceState) { @Override protected void onStart() { super.onStart(); - PreferenceManager.getDefaultSharedPreferences(this) - .registerOnSharedPreferenceChangeListener(this); + + SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); + SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() { + public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { + // Implementation + } + }; + prefs.registerOnSharedPreferenceChangeListener(listener); mRequestLocationUpdatesButton = (Button) findViewById(R.id.request_location_updates_button); mRemoveLocationUpdatesButton = (Button) findViewById(R.id.remove_location_updates_button);