In an android service I have created thread(s) for doing some background task.

I have a situation where a thread needs to post certain task on main thread's message queue, for example a Runnable.

Is there a way to get Handler of the main thread and post Message/Runnable to it from my other thread?

推荐答案

NOTE: This answer has gotten so much attention, that I need to update it. Since the original answer was posted, the comment from @dzeikei has gotten almost as much attention as the original answer. So here are 2 possible solutions:

1. If your background thread has a reference to a Context object:

Make sure that your background worker threads have access to a Context object (can be the Application context or the Service context). Then just do this in the background worker thread:

// Get a handler that can be used to post to the main thread
Handler mainHandler = new Handler(context.getMainLooper());

Runnable myRunnable = new Runnable() {
    @Override 
    public void run() {....} // This is your code
};
mainHandler.post(myRunnable);

2. If your background thread does not have (or need) a Context object

(suggested by @dzeikei):

// Get a handler that can be used to post to the main thread
Handler mainHandler = new Handler(Looper.getMainLooper());

Runnable myRunnable = new Runnable() {
    @Override 
    public void run() {....} // This is your code
};
mainHandler.post(myRunnable);

Java相关问答推荐

Spring Boot@Cachebale批注未按预期工作

在运行MVN测试时,为什么构建失败,并显示了java.lang.ClassNotFoundException:java.net.http.HttpResponse?

SpringBoot+Java 17@Valid未验证POJO

无法初始化JPA实体管理器工厂:无法确定为Java类型<;类>;推荐的JdbcType

放气总是压缩整个街区吗?

如何获取Instant#of EpochSecond(?)的最大值

把一条整型短裤和两条短裤装成一条长的

使用存储在字符串变量中的路径目录打开.pdf文件

扩展视图高度,并将其拖动到较低的视图上,而不是将其向下推?

如何使用Criteria Builder处理一对多关系中的空值?

是否有一个Java Future实现可以在池繁忙时在调用者线程中执行?

如果List是一个抽象接口,那么Collectors.toList()如何处理流呢?

如何使用MapStrCut转换双向链接

在缺少字段时使用Jackson With Options生成Optional.Empty()

不能在 map 上移除折线

无法在IntStream上应用Collectors.groupingBy

如何使用Rascal Evaluator从编译的JAR访问Rascal函数?

将Optionals/null安全添加到嵌套的flatMap/流

如何在 Android Studio 中删除 ImageView 和屏幕/父级边缘之间的额外空间?

如何在 Jenkinsfile 内转义 Maven 中的变量名称