Search code examples
androidsmsbroadcastreceiverandroid-service

Broadcast Receiver within a Service


I am trying to start up a BroadcastReceiver within a Service. What I am trying to do is have a background running service going that collects incoming text messages, and logs incoming phone calls. I figured the best way to go about this is to have a service running that incorporates a broadcast receiver that can catalog either.

How do i go about doing this? I already have my service up and running.


Solution

  • as your service is already setup, simply add a broadcast receiver in your service:

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
       @Override
       public void onReceive(Context context, Intent intent) {
          String action = intent.getAction();
          if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
            //action for sms received
          }
          else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
               //action for phone state changed
          }     
       }
    };
    

    in your service's onCreate do this:

    IntentFilter filter = new IntentFilter();
    filter.addAction("android.provider.Telephony.SMS_RECEIVED");
    filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
    filter.addAction("your_action_strings"); //further more
    filter.addAction("your_action_strings"); //further more
    
    registerReceiver(receiver, filter);
    

    and in your service's onDestroy:

    unregisterReceiver(receiver);
    

    and you are good to go to receive broadcast for what ever filters you mention in onCreate. Make sure to add any permission if required. for e.g.

    <uses-permission android:name="android.permission.RECEIVE_SMS" />