news 2026/5/11 3:21:32

Android 开发 - 子线程到主线程的通信方式(使用 Handler、使用 View 的 post 方法、使用 Activity 的 runOnUiThread 方法等)

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Android 开发 - 子线程到主线程的通信方式(使用 Handler、使用 View 的 post 方法、使用 Activity 的 runOnUiThread 方法等)

一、使用 Handler

TextViewtvContent=findViewById(R.id.tv_content);Handlerhandler=newHandler(Looper.getMainLooper()){@OverridepublicvoidhandleMessage(@NonNullMessagemsg){tvContent.setText("收到消息:"+msg.what);}};newThread(()->{try{Thread.sleep(3*1000);}catch(InterruptedExceptione){e.printStackTrace();}Messagemsg=Message.obtain();msg.what=100;handler.sendMessage(msg);try{Thread.sleep(3*1000);}catch(InterruptedExceptione){e.printStackTrace();}handler.post(()->{tvContent.setText("更新 UI");});}).start();

二、使用 View 的 post 方法

TextViewtvContent=findViewById(R.id.tv_content);newThread(()->{try{Thread.sleep(3*1000);}catch(InterruptedExceptione){e.printStackTrace();}tvContent.post(()->{tvContent.setText("更新 UI");});}).start();

三、使用 Activity 的 runOnUiThread 方法

TextViewtvContent=findViewById(R.id.tv_content);newThread(()->{try{Thread.sleep(3*1000);}catch(InterruptedExceptione){e.printStackTrace();}runOnUiThread(()->{tvContent.setText("更新 UI");});}).start();

四、使用 AsyncTask

TextViewtvContent=findViewById(R.id.tv_content);classMyTaskextendsAsyncTask<String,Integer,String>{@OverrideprotectedStringdoInBackground(String...strings){Stringinput=strings[0];try{Thread.sleep(3*1000);}catch(InterruptedExceptione){e.printStackTrace();}return"处理 【"+input+"】 完成";}@OverrideprotectedvoidonPostExecute(Stringstring){tvContent.setText(string);}}newMyTask().execute("task");

五、使用 LiveData

TextViewtvContent=findViewById(R.id.tv_content);MutableLiveData<String>content=newMutableLiveData<>();content.observe(this,s->{tvContent.setText(s);});newThread(()->{try{Thread.sleep(3*1000);}catch(InterruptedExceptione){e.printStackTrace();}content.postValue("更新 UI");}).start();

六、使用 EventBus

implementation'org.greenrobot:eventbus:3.3.1'
publicclassEventBusTestActivityextendsAppCompatActivity{privateTextViewtvContent;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);EdgeToEdge.enable(this);setContentView(R.layout.activity_event_bus_test);ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main),(v,insets)->{InsetssystemBars=insets.getInsets(WindowInsetsCompat.Type.systemBars());v.setPadding(systemBars.left,systemBars.top,systemBars.right,systemBars.bottom);returninsets;});tvContent=findViewById(R.id.tv_content);newThread(()->{try{Thread.sleep(3*1000);}catch(InterruptedExceptione){e.printStackTrace();}EventBus.getDefault().post("hello event bus");}).start();}@OverrideprotectedvoidonStart(){super.onStart();EventBus.getDefault().register(this);}@OverrideprotectedvoidonStop(){super.onStop();EventBus.getDefault().unregister(this);}@Subscribe(threadMode=ThreadMode.MAIN)publicvoidonMessage(Stringmessage){tvContent.setText(message);}}

七、使用 RxJava

implementation'io.reactivex.rxjava3:rxjava:3.1.8'implementation'io.reactivex.rxjava3:rxandroid:3.0.2'
publicclassRxJavaTestActivityextendsAppCompatActivity{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);EdgeToEdge.enable(this);setContentView(R.layout.activity_rx_java_test);ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main),(v,insets)->{InsetssystemBars=insets.getInsets(WindowInsetsCompat.Type.systemBars());v.setPadding(systemBars.left,systemBars.top,systemBars.right,systemBars.bottom);returninsets;});TextViewtvContent=findViewById(R.id.tv_content);Observable.create((ObservableEmitter<String>emitter)->{TimeUnit.SECONDS.sleep(3);emitter.onNext("test content");}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(data->{tvContent.setText(data);});}}

八、使用 BroadcastReceiver

publicclassBroadcastReceiverTestActivityextendsAppCompatActivity{privateTextViewtvContent;classMyBroadcastReceiverextendsBroadcastReceiver{@OverridepublicvoidonReceive(Contextcontext,Intentintent){Stringmessage=intent.getStringExtra("message");tvContent.setText(message);}}@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);EdgeToEdge.enable(this);setContentView(R.layout.activity_broadcast_receiver_test);ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main),(v,insets)->{InsetssystemBars=insets.getInsets(WindowInsetsCompat.Type.systemBars());v.setPadding(systemBars.left,systemBars.top,systemBars.right,systemBars.bottom);returninsets;});tvContent=findViewById(R.id.tv_content);MyBroadcastReceivermyBroadcastReceiver=newMyBroadcastReceiver();IntentFilterintentFilter=newIntentFilter();intentFilter.addAction(MyBroadcastReceiver.class.getSimpleName());registerReceiver(myBroadcastReceiver,intentFilter);newThread(()->{try{Thread.sleep(3*1000);}catch(InterruptedExceptione){e.printStackTrace();}Intentintent=newIntent(MyBroadcastReceiver.class.getSimpleName());intent.putExtra("message","test content");sendBroadcast(intent);}).start();}}

九、使用协程

classCoroutinesTestActivity:AppCompatActivity(){override funonCreate(savedInstanceState:Bundle?){super.onCreate(savedInstanceState)enableEdgeToEdge()setContentView(R.layout.activity_coroutines_test)ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)){v,insets->val systemBars=insets.getInsets(WindowInsetsCompat.Type.systemBars())v.setPadding(systemBars.left,systemBars.top,systemBars.right,systemBars.bottom)insets}val tvContent=findViewById<TextView>(R.id.tv_content)CoroutineScope(Dispatchers.IO).launch{delay(3000)val message="test content"withContext(Dispatchers.Main){tvContent.text=message}}}}
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/9 8:41:59

【预测模型】天牛须算法优化BP神经网络的电力负荷预测附matlab代码

✅作者简介&#xff1a;热爱科研的Matlab仿真开发者&#xff0c;擅长毕业设计辅导、数学建模、数据处理、建模仿真、程序设计、完整代码获取、论文复现及科研仿真。&#x1f34e; 往期回顾关注个人主页&#xff1a;Matlab科研工作室&#x1f447; 关注我领取海量matlab电子书和…

作者头像 李华
网站建设 2026/5/3 4:46:43

Java计算机毕设之-基于springboot的足球训练营管理系统基于springboot的足球俱乐部青训管理系统的设计与实现(完整前后端代码+说明文档+LW,调试定制等)

博主介绍&#xff1a;✌️码农一枚 &#xff0c;专注于大学生项目实战开发、讲解和毕业&#x1f6a2;文撰写修改等。全栈领域优质创作者&#xff0c;博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、小程序技术领域和毕业项目实战 ✌️技术范围&#xff1a;&am…

作者头像 李华
网站建设 2026/5/8 10:36:16

【计算机毕业设计案例】基于springboot的助农农产品销售平台小程序基于Spring Boot与微信小程序的助农农产品销售平台(程序+文档+讲解+定制)

博主介绍&#xff1a;✌️码农一枚 &#xff0c;专注于大学生项目实战开发、讲解和毕业&#x1f6a2;文撰写修改等。全栈领域优质创作者&#xff0c;博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、小程序技术领域和毕业项目实战 ✌️技术范围&#xff1a;&am…

作者头像 李华
网站建设 2026/4/30 8:59:01

硬核AI技术筑牢根基,Health AI开放平台领跑健康垂直领域智能化赛道

在智慧化健康建设加速落地的当下&#xff0c;企业对健康医疗服务的智能化、专业化、场景化需求日益迫切&#xff0c;却深陷数据割裂、专业门槛高、运营成本高、服务碎片化的困境。作为国内首个专注于健康医疗垂直领域的AI技术开放平台&#xff0c;健康有益Health AI健康云开放平…

作者头像 李华
网站建设 2026/5/2 8:07:26

必收藏!大模型入门核心:预训练完整解析(小白/程序员友好

当ChatGPT、文心一言、Llama等大模型频繁渗透工作与生活&#xff0c;相信很多小白程序员和AI入门者都会产生一个疑问&#xff1a;这些能听懂指令、生成流畅内容的“智能体”&#xff0c;最初是如何学会“读懂语言、理解世界”的&#xff1f;其实答案很简单&#xff0c;核心就藏…

作者头像 李华