背景线程中的Android服务

发布于 2024-12-05 07:09:32 字数 575 浏览 2 评论 0原文

我正在尝试创建一个在给定时间间隔内运行的服务。该服务的目的是更新数据库,并在完成后通过 Intent 通知 Activity

当用户选择“刷新”时,还应该可以从活动中调用该服务。

我已经完成了这一点,但我无法让它在独立线程中运行。

该服务在 Runnable 中执行更新方法:

private Runnable refresh = new Runnable() {
        public void run() {
            update();   //Runs updates
            didUpdate(); //Sends broadcast
            handler.postDelayed(this, 50000); // 50 seconds, calls itself in 50 secs
        }
    };

我有另一个名为 ManualRefresh 的可运行对象,它是通过活动中的广播调用的。

然而,这些可运行对象似乎阻塞了 UI。

需要建议! :)

I'm trying to create a service that runs in a given interval. The service's purpose is to update a database and when done notify an Activity with an Intent.

The service should also be callable from the activity when the user chooses to 'refresh'.

I have accomplished this, but I can't get it to run in a detached thread.

The service executes an update method in a Runnable:

private Runnable refresh = new Runnable() {
        public void run() {
            update();   //Runs updates
            didUpdate(); //Sends broadcast
            handler.postDelayed(this, 50000); // 50 seconds, calls itself in 50 secs
        }
    };

I have another runnable called ManualRefresh that is called via a broadcast from the activity.

However these runnables seem to be blocking the UI.

Need advice! :)

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

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

发布评论

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

评论(2

唱一曲作罢 2024-12-12 07:09:33

我建议使用 armardmanager 。该服务将收到意图,以定期告诉它以更新数据库。

更新后,您可以用意图通知活动(如您提到的)。

当用户想要手动刷新时,请给您提供服务的意图。从AlarmManager或活动中接收意图将执行相同的代码。

您可能还需要在请求手动刷新后重新安排警报。

I suggest to write the service using the AlarmManager. The service will receive an Intent to tell it to periodically to update the database.

Once updated, you can notify the Activity with an Intent (as you mentioned).

When the user wants to manually refresh, have the Application sent an Intent to you service. Receiving the Intent from the AlarmManager or from the Activity would perform the same code.

You may also want to reschedule the alarm after a request to manually refresh.

计㈡愣 2024-12-12 07:09:32

当您通过调用 Runnable 的 run 方法来运行它时,它会在当前线程上运行。要在后台线程上运行,您需要使用 new Thread(refresh).start(); (如果您要运行的 Runnable 是 refresh)。

您还可以为此使用 AsyncTask,但这更适合活动而不是服务。有关使用 AsyncTask 的信息可以在 API 文档 和文章中找到无痛线程

When you run a Runnable by calling it's run method, it runs on the current thread. To run on a background thread, you need to use new Thread(refresh).start(); (if the Runnable you want run is refresh).

You can also make use of AsyncTask for this, but that's more appropriate for an activity than for a Service. Information about using AsyncTask can be found in the API docs and in the article Painless Threading.

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