从服务访问 UI 线程处理程序 [英] Accessing UI thread handler from a service

查看:29
本文介绍了从服务访问 UI 线程处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Android 上尝试一些新的东西,我需要访问 UI 线程的处理程序.

I am trying some thing new on Android for which I need to access the handler of the UI thread.

我知道以下几点:

  1. UI 线程有自己的处理程序和活套
  2. 任何消息都会被放入进入UI的消息队列线程
  3. looper 接手事件并将其传递给处理程序
  4. 处理程序处理消息并将特定事件发送到 UI

我想要我的服务,它必须获取 UI 线程处理程序并将消息放入此处理程序中.以便此消息将被处理并将被发布到 UI.这里的服务将是一个普通的服务,由某个应用程序启动.

I want to have my service which has to get the UI thread handler and put a message into this handler. So that this message will be processed and will be issued to the UI. Here the service will be a normal service which will be started by some application.

我想知道这是否可能.如果是这样,请建议一些代码片段,以便我可以尝试.

I would like to know if this is possible. If so please suggest some code snippets, so that I can try it.

问候女孩

推荐答案

这段代码构造了一个与主 (UI) 线程关联的 Handler:

This snippet of code constructs a Handler associated with the main (UI) thread:

Handler handler = new Handler(Looper.getMainLooper());

然后您可以像这样在主(UI)线程中发布要执行的内容:

You can then post stuff for execution in the main (UI) thread like so:

handler.post(runnable_to_call_from_main_thread);

如果处理程序本身是从主 (UI) 线程创建的,则为简洁起见,可以省略该参数:

If the handler itself is created from the main (UI) thread the argument can be omitted for brevity:

Handler handler = new Handler();

有关进程和线程的 Android 开发指南提供了更多信息.

The Android Dev Guide on processes and threads has more information.

这篇关于从服务访问 UI 线程处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆