Skip to content

Instantly share code, notes, and snippets.

@amritlalsahu5
Created February 15, 2020 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amritlalsahu5/a21d68b4dd7c2505d6b37e66aa188417 to your computer and use it in GitHub Desktop.
Save amritlalsahu5/a21d68b4dd7c2505d6b37e66aa188417 to your computer and use it in GitHub Desktop.
package com.codehangouts.sampleapp.memoryleak.kotlin.thread.handlers
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.example.myapplication.R
import java.lang.ref.WeakReference
class HandlerReferenceActivity : AppCompatActivity() {
private val title: TextView? = null
private val innerHandler = InnerHandler(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
/*
* Commented lines is responsible for memory leaks as it holds implicit
* reference of Activity.
* */
/*new Handler().postDelayed(new Runnable() {
@Override
public void run() {
title.setText(getString(R.string.title_dashboard));
}
}, 2000);*/
/*
Instead create static class for handler and runnable both.
*/
innerHandler.postDelayed(handlerRunnable, 2000)
}
private class InnerHandler(activity: HandlerReferenceActivity) : Handler() {
/*
* Fix for reference - Use weak reference instead of directly holding
* the activity reference.
* */
private val weakReferenceActivity: WeakReference<HandlerReferenceActivity>
init {
weakReferenceActivity = WeakReference(activity)
}
override fun handleMessage(msg: Message) {
val activity = weakReferenceActivity.get()
if (activity != null) {
activity.title!!.text = activity.getString(R.string.title_dashboard)
}
}
}
companion object {
private val handlerRunnable = Runnable { /* ... */ }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment