register receiver in a service

If you want to only receive the broadcast while your service is running you will need to dynamically register your receiver in onCreate()

Also it is important to not forget to unregister your receiver in the onDestroy() method!


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.widget.Toast;

public class YourClass extends Service {

    private static final String ACTION="android.provider.Telephony.SMS_RECEIVED";
    private BroadcastReceiver yourReceiver;

    public IBinder onBind(Intent arg0) {
        return null;

    public void onCreate() {
        final IntentFilter theFilter = new IntentFilter();
        this.yourReceiver = new BroadcastReceiver() {

            public void onReceive(Context context, Intent intent) {
                // Do whatever you need it to do when it receives the broadcast
                // Example show a Toast message...
        // Registers the receiver so that your service will listen for
        // broadcasts
        this.registerReceiver(this.yourReceiver, theFilter);

    public void onDestroy() {
        // Do not forget to unregister the receiver!!!

    private void showSuccessfulBroadcast() {
        Toast.makeText(this, "Broadcast Successful!!!", Toast.LENGTH_LONG)

Leave a Comment