gpt4 book ai didi

android - Android中的服务与线程

转载 作者:IT老高 更新时间:2023-10-28 22:16:27 25 4
gpt4 key购买 nike

我正在寻找应该在 android 应用程序中使用什么服务。

文档说

A Service is an application component that can perform long-running operations in the background and does not provide a user interface.

我已阅读此主题 Application threads vs Service threads也就是说,相同的服务用于在后台运行操作。

但是这里也可以使用 Thread 来完成。它们之间的任何区别以及您应该在哪里使用它们

最佳答案

根据最新文档更新:

Android 已在其文档中包含有关何时应使用服务与线程的信息。它是这样说的:

If you need to perform work outside your main thread, but only while the user is interacting with your application, then you should probably instead create a new thread and not a service. For example, if you want to play some music, but only while your activity is running, you might create a thread in onCreate(), start running it in onStart(), then stop it in onStop(). Also consider using AsyncTask or HandlerThread, instead of the traditional Thread class. See the Processes and Threading document for more information about threads.

Remember that if you do use a service, it still runs in your application's main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations.

这两种方法的另一个显着区别是,如果您的设备休眠,Thread 将休眠。然而,即使设备进入休眠状态,Service 也可以执行操作。让我们以使用这两种方法播放音乐为例。

线程方法:只有在您的应用处于 Activity 状态或屏幕显示打开时才会播放音乐。

服务方式:即使你最小化你的应用或屏幕关闭,音乐仍然可以播放。

注意:从 API 级别 23 开始,您应该 Test your app with Doze .

Android Documentation - Services

关于android - Android中的服务与线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22933762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com