Created
February 15, 2020 13:55
-
-
Save amritlalsahu5/6ae09599b2926ea2453ee616c4093823 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.broadcast | |
import android.app.Activity | |
import android.content.BroadcastReceiver | |
import android.content.Context | |
import android.content.Intent | |
import android.content.IntentFilter | |
import android.os.Bundle | |
import com.example.myapplication.R | |
class LocalBroadcastReceiverActivity : Activity() { | |
private var localBroadcastReceiver: BroadcastReceiver? = null | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
} | |
private fun registerBroadCastReceiver() { | |
localBroadcastReceiver = object : BroadcastReceiver() { | |
override fun onReceive(context: Context, intent: Intent) { | |
//Write your code here. | |
} | |
} | |
registerReceiver(localBroadcastReceiver, IntentFilter("android.net.conn.CONNECTIVITY_CHANGE")) | |
} | |
override fun onStart() { | |
super.onStart() | |
registerBroadCastReceiver() | |
} | |
override fun onStop() { | |
super.onStop() | |
/* | |
* Broadcast receiver holds the implicit reference of Activity.Therefore even if activity is destroy, | |
* garbage collector will not be able to remove its instance. | |
* */ | |
if (localBroadcastReceiver != null) { | |
unregisterReceiver(localBroadcastReceiver) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment