From 34c539520073da60cf28755e48009ce614c1eb39 Mon Sep 17 00:00:00 2001 From: Christian Rowlands Date: Thu, 22 Feb 2024 08:45:56 -0500 Subject: [PATCH] Memory Leak hunting, fixed a memory leak where the service connection was not unbinded --- .../mqttlibrary/ui/AConnectionFragment.java | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/MqttLibrary/src/main/java/com/craxiom/mqttlibrary/ui/AConnectionFragment.java b/MqttLibrary/src/main/java/com/craxiom/mqttlibrary/ui/AConnectionFragment.java index 55a83e6..ba1e28a 100755 --- a/MqttLibrary/src/main/java/com/craxiom/mqttlibrary/ui/AConnectionFragment.java +++ b/MqttLibrary/src/main/java/com/craxiom/mqttlibrary/ui/AConnectionFragment.java @@ -54,6 +54,8 @@ */ public abstract class AConnectionFragment extends Fragment implements IConnectionStateListener { + protected final SurveyServiceConnection surveyServiceConnection = new SurveyServiceConnection(); + private static final int ACCESS_PERMISSION_REQUEST_ID = 10; private final Handler uiThreadHandler; @@ -254,7 +256,19 @@ public void onResume() @Override public void onPause() { - if (service != null) service.unregisterMqttConnectionStateListener(this); + try + { + requireContext().getApplicationContext().unbindService(surveyServiceConnection); + } catch (Throwable t) + { + Timber.e(t, "Could not unbind the service because it is not bound."); + } + + if (service != null) + { + service.unregisterMqttConnectionStateListener(this); + service = null; + } super.onPause(); } @@ -263,6 +277,10 @@ public void onPause() public void onDestroyView() { hideSoftInputFromWindow(); + + applicationContext = null; + service = null; + super.onDestroyView(); } @@ -757,7 +775,6 @@ private void startAndBindToService() applicationContext.startService(serviceIntent); // Bind to the service - ServiceConnection surveyServiceConnection = new SurveyServiceConnection(); final boolean bound = applicationContext.bindService(serviceIntent, surveyServiceConnection, Context.BIND_ABOVE_CLIENT); Timber.i("%s service bound in the AConnectionFragment: %s", getServiceClass().getSimpleName(), bound); } catch (Exception e)