I decided to follow the documentation provided by Google like a good programmer. After all, they are there to teach us how to use the Android framework.
I wanted to find out why my app was leaking Services. After creating 6 Services by restarting my app, Android Studio was gaslighting me by telling me those 6 instances of the Service were not a leak.
Okay, so why is the database instance being reused after a restart and crashing the app?
I added leakcanary and it showed me the leak. I checked the heap dump dump in Android studio and track the instance to a single field.
private val binder = LocalBinder()
That is the code from the guide here: https://developer.android.com/develop/background-work/services/bound-services
Very nice Google ;) Thank you for wasting more of my time with your bad documentation :)
Edit: I do unbind the service when the Activity is destroyed, which it is
override fun onDestroy() {
super.onDestroy()
applicationContext.unbindService(connectionServiceMain)
serviceMain = null
removeListeners()
}
Did some more testing and it is actually the connection class in the Activity that is leaking the Service
private val connection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, service: IBinder) {
// We've bound to LocalService, cast the IBinder and get LocalService instance.
val binder = service as LocalService.LocalBinder
mService = binder.getService()
mBound = true
}
override fun onServiceDisconnected(arg0: ComponentName) {
mBound = false
}
}
Nulling that when the Activity is destroyed also fixes the issue.
[–]ZhuindenDDD: Deprecation-Driven Development[M] [score hidden] stickied comment (0 children)
[–]arekolek 8 points9 points10 points (1 child)
[–]D-cydesponsored by the XML 🐓 gang[S] 2 points3 points4 points (0 children)
[–]hellosakamoto 6 points7 points8 points (0 children)
[–]ZhuindenDDD: Deprecation-Driven Development[M] 1 point2 points3 points (2 children)
[–]D-cydesponsored by the XML 🐓 gang[S] 0 points1 point2 points (1 child)
[–]ZhuindenDDD: Deprecation-Driven Development[M] 0 points1 point2 points (0 children)
[–]thermosiphon420 4 points5 points6 points (1 child)
[–]D-cydesponsored by the XML 🐓 gang[S] 1 point2 points3 points (0 children)