Search code examples
androidbroadcastreceiverbroadcastandroid-broadcastandroid-broadcastreceiver

Perform long running operations when receiving SMS on API < 21


I'm building an app that will listen for incoming SMS messages, perform some potentially long running operations and send back a reply if some conditions are met.

I've got the listening part working using a BroadcastReceiver, but I'm not sure how/where to perform the potentially long running operations. The Android Developer Documentation states that

After onReceive(), the system can kill the process at any time to reclaim memory, and in doing so, it terminates the spawned thread running in the process. To avoid this, you should either call goAsync() (if you want a little more time to process the broadcast in a background thread) or schedule a JobService from the receiver using the JobScheduler, so the system knows that the process continues to perform active work.

And also:

Calling goAsync() in your receiver's onReceive() method and passing the BroadcastReceiver.PendingResult to a background thread. This keeps the broadcast active after returning from onReceive(). However, even with this approach the system expects you to finish with the broadcast very quickly (under 10 seconds). It does allow you to move work to another thread to avoid glitching the main thread.

Furthermore, JobScheduler is not available on API < 21.

So how would I achieve this on API 16 - 20?


Solution

  • Just start a Service in your BroadcastReceiver to do the long-running operation and send back the result. You could use an IntentService or a regular Service.