register receiver in a service
You must set permissions in the AndroidManifest file.
<receiver android:name=".MySMSReciever">
<intent-filter>
<action android:name=
"android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
How do I implement a BroadcastReceiver in a Service Class in Android?
Have the BroadcastReceiver as a top-level class or as an inner class in your service. And get a reference of the receiver in your service. Like this:
public class MyService extends Service {
BroadcastReceiver mReceiver;
// use this as an inner class like here or as a top-level class
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// do something
}
// constructor
public MyReceiver(){
}
}
@Override
public void onCreate() {
// get an instance of the receiver in your service
IntentFilter filter = new IntentFilter();
filter.addAction("action");
filter.addAction("anotherAction");
mReceiver = new MyReceiver();
registerReceiver(mReceiver, filter);
}
}
Register a broadcast receiver from a service in a new thread
In your service's onCreate()
:
private Handler handler; // Handler for the separate Thread
HandlerThread handlerThread = new HandlerThread("MyNewThread");
handlerThread.start();
// Now get the Looper from the HandlerThread so that we can create a Handler that is attached to
// the HandlerThread
// NOTE: This call will block until the HandlerThread gets control and initializes its Looper
Looper looper = handlerThread.getLooper();
// Create a handler for the service
handler = new Handler(looper);
// Register the broadcast receiver to run on the separate Thread
registerReceiver (myReceiver, intentFilter, broadcastPermission, handler);
Programmatically register a broadcast receiver
It sounds like you want to control whether components published in your manifest are active, not dynamically register a receiver (via Context.registerReceiver()) while running.
If so, you can use PackageManager.setComponentEnabledSetting() to control whether these components are active:
http://developer.android.com/reference/android/content/pm/PackageManager.html#setComponentEnabledSetting(android.content.ComponentName, int, int)
Note if you are only interested in receiving a broadcast while you are running, it is better to use registerReceiver(). A receiver component is primarily useful for when you need to make sure your app is launched every time the broadcast is sent.
BroadcastReceiver in Service Android
When your target is to listen for phone state changes in the Service
class itself. You can try to define it internally within the Service
. This will decrease resource usage too as the system is not burdened with handling the lifecycle of another component. In your Service
:
private final PhoneStateListener mPhoneListener = new PhoneStateListener() {
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
// Call receive state
if (state != TelephonyManager.CALL_STATE_IDLE) {
// Do something
}
}
};
Then you can register it to listen as (probably in onStartCommand()
):
TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
mTelephonyManager.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
And then unregister it from listening in onDestroy()
(or whenever you are done):
mTelephonyManager.listen(mPhoneListener, PhoneStateListener.LISTEN_NONE);
how to register broadcast receiver in intent service
Instead of registering in onCreate()
and unregistering in onDestroy()
methods, I changed the sendSMS
method to following:
public void sendSMS(String number,String message,String serialnum)
{
String DELIVERED = "SMS_DELIVERED";
Intent delivered = new Intent(DELIVERED);
delivered.putExtra("MsgNum", serialnum);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, delivered, 0);
registerReceiver(
new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",Toast.LENGTH_SHORT).show();
updateSMSStatus USS = new updateSMSStatus();
USS.execute(intent.getStringExtra("Msgnum"));
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",Toast.LENGTH_SHORT).show();
break;
}
unregisterReceiver(this);
}
},
new IntentFilter(DELIVERED));
SmsManager smsMngr = SmsManager.getDefault();
smsMngr.sendTextMessage(number, null, message, null, deliveredPI);
}
The sms delivered action is now triggered, thanks all.
Any ideas on how to differentiate the delivery reports of each sms?
I'm not pretty sure on how to use the intent.putExtra()
method in my service
with the delivery BroadcastReceiver
.
Related Topics
Android, How to Exec a SQL File in Sqlitedatabase
Changing Values from Cursor Using Simplecursoradapter
How to Add a Custom Item to a Navigationview with a Menu Layout
Evenly Spaced Menu Items on Toolbar
Putting Screen Densities into The Correct Bucket
Does Android Studio Have a Hierarchy Viewer or Layout Inspector
Handle Screen Orientation Changes When There Are Asynctasks Running
Android Get Application's 'Home' Data Directory
Android Service to Check Internet Connectivity
Android Studio Could Not Find Any Version That Matches Com.Android.Support:Appcompat-V7:+
Action Bar Back Button Not Working
How to Launch Android Calendar Application Using Intent (Froyo)
Android: How to Programmatically Set Layout_Constraintright_Torightof "Parent"