I have an extended class of BroadcastReceiver
in MainActivity.java I launch the listener
registerReceiver(
new ConnectivityChangeReceiver(),
new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
I find that when I exit the app it shows me the following error in the log:
E/ActivityThread: Activity com.webserveis.app.myconnection.MainActivity has leaked IntentReceiver com.webserveis.app.myconnection.ConnectivityChangeReceiver@32ad932e that was originally registered here. Are you missing a call to unregisterReceiver()? android.app.IntentReceiverLeaked: Activity com.webserveis.app.myconnection.MainActivity has leaked IntentReceiver com.webserveis.app.myconnection.ConnectivityChangeReceiver@32ad932e that was originally registered here. Are you missing a call to unregisterReceiver()?
that was originally registered here. Are you missing a call to unregisterReceiver()
In onStop()
I would like to unregister the listener, but not how to implement it
When implementing a BroadcastReceiver , it is important to know that we have to register and unregister the receiver, but it is NOT good practice to cancel the receiver in onStop() and this is why, which you can see in the documentation:
When your implementation requires logging in
onResume()
there is an important consideration .Regarding your error:
the documentation itself states:
Therefore :
I add an example:
You should store your
BroadcastReceiver
in a variable of yourMainActivity
and in youronStop()
putunregisterReceiver(myBroadcastReceiver);
You must take into account that if you go through it
onStop()
without havingBroadcastReceiver
previously registered it, an exception will be thrown.All the best