I have a BroadcastReceiver that I create dynamically in a Service. Its purpose is to detect when an SMS has been sent. It works as expected.
My trouble is that I receive an error saying "the Intent Receiver has leaked". Am I missing a call to unregisterReceiver()
?
I am making the call to unregisterReceiver()
in onDestroy()
. I guess this must be wrong. Where should I unregister the receiver?
Code...
public class MyService extends Service {
BroadcastReceiver brSms;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
}
@Override
public void onStart(Intent intent, int startid) {
//Define the receiver
brSms = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//Do some stuff
};
}
registerReceiver(brSms, new IntentFilter(SENT_SMS_ACTION));
}
@Override
public void onDestroy() {
unregisterReceiver(brSms);
Toast.makeText(this, "onDestroy has been called", Toast.LENGTH_SHORT).show();
}
}//end of MyService
You should register and unregister your broadcast in onResume() and onPause() methods. if you register in onStart() and unregister it in onStop().
To stop receiving broadcasts, call unregisterReceiver(android. content. BroadcastReceiver) . Be sure to unregister the receiver when you no longer need it or the context is no longer valid.
Currently there is no way to check if a receiver is registered using the receiver reference. You have to unregister the receiver and catch the IllegalArgumentException that is thrown if it's not registered. This is ugly, and a boolean method to check if it's registered would be helpful.
It's always suggested to register and unregister broadcast receiver programmatically as it saves system resources.
Try like this:
public class MyService extends Service {
BroadcastReceiver brSms;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
brSms = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//Do some stuff
}
};
registerReceiver(brSms, new IntentFilter(SENT_SMS_ACTION));
}
@Override
public void onStart(Intent intent, int startid) {
}
@Override
public void onDestroy() {
unregisterReceiver(brSms);
Toast.makeText(this, "onDestroy has been called", Toast.LENGTH_SHORT).show();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With