栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java从另一个线程在主线程中运行代码

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java从另一个线程在主线程中运行代码

注意:此答案已引起广泛关注,我需要对其进行更新。自从原始答案发布以来,@ dzeikei的评论几乎和原始答案一样受到关注。因此,这里有两种可能的解决方案:

1.如果您的后台线程引用了一个

Context
对象:

确保您的后台工作线程可以访问Context对象(可以是Application上下文或Service上下文)。然后只需在后台工作线程中执行此操作:

// Get a handler that can be used to post to the main threadHandler mainHandler = new Handler(context.getMainLooper());Runnable myRunnable = new Runnable() {    @Override     public void run() {....} // This is your pre};mainHandler.post(myRunnable);

2.如果您的后台线程没有(或不需要)

Context
对象

(由@dzeikei建议):

// Get a handler that can be used to post to the main threadHandler mainHandler = new Handler(Looper.getMainLooper());Runnable myRunnable = new Runnable() {    @Override     public void run() {....} // This is your pre};mainHandler.post(myRunnable);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/517652.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号