Created
February 15, 2020 13:56
-
-
Save amritlalsahu5/a21d68b4dd7c2505d6b37e66aa188417 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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