我是一个完全的初学者和Android Studio。 从本质上讲,我正在尝试创建一段代码,在应用程序背景下进行定期检查,但我不确定如何执行此操作。 我需要使用后台服务还是其他什么?
我真的很感激任何帮助。
I'm a complete beginner here and with Android Studio. Essentially, I'm trying to create a piece of code that does periodic checks whilst the app is backgrounded, however I'm unsure as to how to do this. Would I need to use a background service or something else?
I'd really appreciate any help.
最满意答案
首先,您需要一项服务。 服务是一段代码,没有用于后台任务的UI,或者应该在活动之间持续的持久操作。
其次,您需要定期轮询。 这可以通过报警或通过线程完成。 UI线程上将发生警报,线程是并行的,但您需要考虑所有正常的并行处理问题。 一个线程在很多方面都比较简单,因为你可以在它上面睡觉()等待你下一次做检查。 哪个更好取决于你的用例。
First you need a Service. A Service is a piece of code with no UI meant for background tasks, or for long lasting operations that should last between Activities.
Second, you need to poll periodically. That can be done either via an Alarm or via a Thread. An Alarm will occur on the UI thread, a Thread is parallel but you need to take all the normal parallel processing issues into account. A thread is simpler in many ways though as you can just sleep() on it to wait for your next time to do checks. Which is better depends on your usecase.
更多推荐
发布评论