Perform long running operations when receiving SMS on API < 21

戏子无情 提交于 2019-12-13 20:24:11

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/52407154/perform-long-running-operations-when-receiving-sms-on-api-21

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!