在 API < 21 上接收短信时执行长 运行 操作
Perform long running operations when receiving SMS on API < 21
我正在构建一个应用程序,它将侦听传入的 SMS 消息,执行一些可能很长的 运行 操作,并在满足某些条件时发回回复。
我的听力部分使用 BroadcastReceiver
,但我不确定 how/where 是否可以执行可能很长的 运行 操作。 Android Developer Documentation 表示
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.
还有:
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.
此外,JobScheduler
不适用于 API < 21。
那么我如何在 API 16 - 20 日实现这一点?
只需在您的 BroadcastReceiver
中启动一个 Service
来执行 long-运行 操作并发回结果。您可以使用 IntentService
或常规 Service
.
我正在构建一个应用程序,它将侦听传入的 SMS 消息,执行一些可能很长的 运行 操作,并在满足某些条件时发回回复。
我的听力部分使用 BroadcastReceiver
,但我不确定 how/where 是否可以执行可能很长的 运行 操作。 Android Developer Documentation 表示
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.
还有:
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.
此外,JobScheduler
不适用于 API < 21。
那么我如何在 API 16 - 20 日实现这一点?
只需在您的 BroadcastReceiver
中启动一个 Service
来执行 long-运行 操作并发回结果。您可以使用 IntentService
或常规 Service
.