android中如何将activity转为service?

发布于 2024-11-25 12:01:07 字数 141 浏览 1 评论 0原文

我是 android 新手,我编写了一个程序来显示 android 用户的位置,并通过网络服务将其发送到服务器。在我的应用程序中,我希望它在后台运行,同时屏幕上显示名称列表和其他进程。我搜索过这个,发现服务可以在后台运行,我想知道是否有人对如何将其变成服务有任何建议?

I am new to android and I have written a program that displays the location of the android user and also sends it via a web service to a server. In my application I wanted this to run in the background while a list of names and other processes are going on the screen. I have searched this and found that a service can be run in the background and I was wondering if anyone had any suggestions on how to turn this into a service?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

绝不服输 2024-12-02 12:01:07

服务并不是最好的用途。服务在后台运行,但它们与应用程序的主 UI 线程在同一线程上运行。如果用户不直接与应用程序交互,这很好。例如,如果您有一个将文件加载到服务器的应用程序,则可以使用一个按钮来启动服务来加载文件并关闭应用程序的活动,同时服务继续在后台运行。文件加载后,您可以弹出文件已加载的通知或直接关闭服务。

当活动在前台运行时运行的服务可能会阻止该活动。因此,您不想使用服务来实现此目的,因为当服务下载或上传某些内容到服务器时,UI 不会更新

。您想要的是 AsyncTask。 AsyncTask 是一个一次性线程处理程序,允许您在更新 UI 的同时执行高强度工作。

http://developer.android.com/reference/android/os/AsyncTask.html

如果你想连续这样做,那么AsyncTask可能不起作用。在这种情况下,您可以使用 Java 计时器或标准 Java 线程来处理连续工作。请注意,您永远不想从 UI 线程之外的任何其他线程更新 UI。它最终会让你的应用程序崩溃。

A service would not be the best use for this. Services run in the background, but they run on the same thread as the main UI thread of the application. This is fine if the user is not directly interacting with the application. For example, if you have an app that loads a file to a server, you can have a button that starts the service to load the file and close the activity for the app while the service continues to run in the background. Once the file is loaded, you can pop up a notification that the file was loaded or just shut the service down.

Service that run while the activity is running in the foreground can block the activity. Thus, you don't want to use a Service for this purpose as the UI won't update while a service is downloading or uploading something to a server

What you want is an AsyncTask. AsyncTask is a one-shot thread handler that allows you to do high-intensive work while updating the UI.

http://developer.android.com/reference/android/os/AsyncTask.html

If you want to do this continuously, then AsyncTask may not work. In this case, you can use Java timers or standard Java threads to handle continuous work. Just note that you NEVER want to update the UI from any other thread than the UI thread. It will make your app crash eventually.

盛夏尉蓝 2024-12-02 12:01:07

阅读 SDK 中的 Service 类文档,它包含您想了解的所有内容以及示例。

Read the Service class documentation in the SDK, it has all you want to know plus examples.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文