

Android入门第37天-在子线程中调用Handler
source link: https://blog.csdn.net/lifetragedy/article/details/128168389
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Android入门第37天-在子线程中调用Handler_TGITCIC的博客-CSDN博客_android 子线程handler
前一章我们以一个简单的小动画来解释了Handler。
这章我们会介绍在子线程里写Handler。如果是Handler写在了子线程中的话,我们就需要自己创建一个Looper对象了:创建的流程如下:
- 直接调用Looper.prepare()方法即可为当前线程创建Looper对象,而它的构造器会创建配套的MessageQueue;
- 创建Handler对象,重写handleMessage( )方法就可以处理来自于其他线程的信息了!
- 调用Looper.loop()方法启动Looper
使用示例: 输入一个数,计算后通过Toast输出在这个范围内的所有质数,如下截图。


很简单,前端有一个输入框一个按钮。
来看后端代码

后端代码我们使用的是求给定数字范围内有几个质数里比较高效的一种算法。
关键在于:
- 使用线程,在线程开始我们使用:Loop.prepare,在运算完后使用Loop.loop();
- 使用mHandler = new Handler(new Handler.Callback()进行监听;
- 使用message发送主界面输入的“质数”给到在监听的mHandler;
- 当mHandler监听到有消息到达后开始运算质数集,运算后把结果以Toast输出
自己动一手吧。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK