Android 实战之UI线程和Worker线程交互
哈哈,博文取了个比较霸气的名字,大家不都喜欢这样忽悠人吗 呵呵!
好了,现在就是很简单的点击查询,然后这个查询有点花时间,不想见面出现假死现象,所以在另外的线程进行查询。
好了,代码在此:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | package com.example.gulanfinddemo; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import android.widget.EditText; public class FindResActivity extends Activity { private MyHandler handler; private Boolean isKeywordFindBoolean = false ; EditText resText; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_find_res); resText = (EditText)findViewById(R.id.ResText); Log.v( "FindResActivity threadId:" , String.valueOf(Thread.currentThread().getId())); Intent intent = getIntent(); String findReString; if ( null != intent.getStringExtra(MainActivity.suraAyaFindStr)) { findReString = "按章节查询" ; isKeywordFindBoolean = false ; } else { findReString = "按关键字查询" ; isKeywordFindBoolean = true ; } Looper looper = Looper.myLooper(); handler = new MyHandler(looper); new findContentThread(handler, findReString).start(); //resText.setText(findReString); } private class MyHandler extends Handler{ public MyHandler(Looper looper){ super (looper); } public void handleMessage(Message msg){ if (msg.what == 0 ) { Bundle bundle = msg.getData(); resText.setText(bundle.getString( "res" )); } } } } |
看出来了,重载了handler,在
1 | handleMessage里会进行UI的更新。 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | package com.example.gulanfinddemo; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; public class findContentThread extends Thread{ private String queryKeyString; private Handler handler; public findContentThread(Handler sendHandler,String string){ queryKeyString = string; handler = sendHandler; } public void run(){ Log.v( "findContentThread threadId:" , String.valueOf(Thread.currentThread().getId())); Message msgMessage = new Message(); Bundle bundle = new Bundle(); bundle.putString( "res" , queryKeyString); msgMessage.setData(bundle); msgMessage.what = 0 ; handler.sendMessage(msgMessage); super .run(); } } |
在这里用了扩展Thread的方法,处理之后handler会传回消息,之后就在handler里处理消息了。
然后里面打印了线程ID,从其中可以确定的确是在不同的线程里执行的。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 字符编码:从基础到乱码解决
2011-10-18 PCA之后进行归一化
2011-10-18 PCA应用1