I'm monitoring incoming SMSs.
My app is working perfectly with a BroadcastReceiver
. However it is working from an Activity and would like to keep the BroadcastReceiver
running all the time (and not just when my Activity is running).
How can I achieve this? I've looked through the lifecycle of the BroadcastReceiver
but all that is mentioned in the documentation is that the lifecycle is limited to the onReceive
method, not the lifecycle of keeping the BroadcastReceiver
checking for incoming SMS.
How can I make this persistent?
Thanks
You need to define a receiver in manifest with action name android.intent.action.BOOT_COMPLETED.
Make sure also to include the completed boot permission.
Use Service for this to make anything persist. And use receivers to receive Boot Up events to restart the service again if system boots..
Code for Starting Service on boot up. Make Service do your work of checking sms or whatever you want. You need to do your work in
MyPersistingService
define it your self.Service or Boot Completed is not mandatory
In fact, you don't need to implement a
Service
or register toandroid.intent.action.BOOT_COMPLETED
Some examples shows how to register/unregister a
BroadcastReceiver
when activity is created and destroyed. However, this is useful for intents that you expect only when app is opened (for internal communication between Service/Activity for example).However, in case of a SMS, you want to listen to the intent all the time (and not only when you app is opened).
There's another way
You can create a
class
which extendsBroadcastReceiver
and register to desired intents viaAndroidManifest.xml
. This way, theBroadcastReceiver
will be indepedent from your Activity (and will not depend from Activity's Life Cycle)This way, your
BroadcastReceiver
will be notified automatically by Android as soon as an SMS arrive even if your app is closed.AndroidManifest.xml
MyCustomBroadcastReceiver.java
Notes
You can add others intent-filters to AndroidManifest and handle all of them in same
BroadcastReceiver
.Start a Service only if you will perform a long task. You just need to display a notification or update some database, just use the code above.