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.
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.
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.
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.
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.
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" />
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