Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 879
Utopia025 Avatar asked Feb 01 '12 07:02

Utopia025


People also ask

Is broadcast receiver a service?

A Broadcast Receiver is a system listener (events from the OS), or listener to other apps. Service is what you use internally in your App.

What is the difference between broadcast receiver and a service?

A Service receives intents that were sent specifically to your application, just like an Activity. A Broadcast Receiver receives intents that were broadcast system-wide to all apps installed on the device.

What is a broadcast receiver?

Broadcast Receiver Overview. A broadcast receiver is an Android component that allows an application to respond to messages (an Android Intent ) that are broadcast by the Android operating system or by an application.

When would you use a broadcast receiver?

Broadcast in android is the system-wide events that can occur when the device starts, when a message is received on the device or when incoming calls are received, or when a device goes to airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events.


1 Answers

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" /> 
like image 195
waqaslam Avatar answered Oct 27 '22 13:10

waqaslam