如何使用Android Studio创建一段后台代码(How would I create a piece of background code using Android Studio)

编程入门 行业动态 更新时间:2024-10-18 20:27:40
如何使用Android Studio创建一段后台代码(How would I create a piece of background code using Android Studio)

我是一个完全的初学者和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.

更多推荐

本文发布于:2023-08-03 13:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1390651.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   后台   代码   Studio   Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!