android主线程和子线程之间消息传递详解
作者:野比大雄-蜗牛 时间:2021-11-06 05:06:23
从主线程发送消息到子线程(准确地说应该是非UI线程)
package com.zhuozhuo;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
public class LooperThreadActivity extends Activity{
/** Called when the activity is first created. */
private final int MSG_HELLO = 0;
private Handler mHandler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new CustomThread().start();//新建并启动CustomThread实例
findViewById(R.id.send_btn).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {//点击界面时发送消息
String str = "hello";
Log.d("Test", "MainThread is ready to send msg:" + str);
mHandler.obtainMessage(MSG_HELLO, str).sendToTarget();//发送消息到CustomThread实例
}
});
}
class CustomThread extends Thread {
@Override
public void run() {
//建立消息循环的步骤
Looper.prepare();//1、初始化Looper
mHandler = new Handler(){//2、绑定handler到CustomThread实例的Looper对象
public void handleMessage (Message msg) {//3、定义处理消息的方法
switch(msg.what) {
case MSG_HELLO:
Log.d("Test", "CustomThread receive msg:" + (String) msg.obj);
}
}
};
Looper.loop();//4、启动消息循环
}
}
}
从非UI线程传递消息到UI线程(界面主线程),因为主界面已经有MessageQueue,所以可以直接获取消息处理消息。而上面由主线程向非UI线程中处理消息的时候,非UI线程需要先添加消息队列,然后处理消息循环。
public class ThreadHandlerActivity extends Activity {
/** Called when the activity is first created. */
private static final int MSG_SUCCESS = 0;//获取图片成功的标识
private static final int MSG_FAILURE = 1;//获取图片失败的标识
private ImageView mImageView;
private Button mButton;
private Thread mThread;
private Handler mHandler = new Handler() {
public void handleMessage (Message msg) {//此方法在ui线程运行
switch(msg.what) {
case MSG_SUCCESS:
mImageView.setImageBitmap((Bitmap) msg.obj);//imageview显示从网络获取到的logo
Toast.makeText(getApplication(), getApplication().getString(R.string.get_pic_success), Toast.LENGTH_LONG).show();
break;
case MSG_FAILURE:
Toast.makeText(getApplication(), getApplication().getString(R.string.get_pic_failure), Toast.LENGTH_LONG).show();
break;
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mImageView= (ImageView) findViewById(R.id.imageView);//显示图片的ImageView
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(mThread == null) {
mThread = new Thread(runnable);
mThread.start();//线程启动
}
else {
Toast.makeText(getApplication(), getApplication().getString(R.string.thread_started), Toast.LENGTH_LONG).show();
}
}
});
}
Runnable runnable = new Runnable() {
@Override
public void run() {//run()在新的线程中运行
HttpClient hc = new DefaultHttpClient();
HttpGet hg = new HttpGet("http://csdnimg.cn/www/images/csdnindex_logo.gif");//获取csdn的logo
final Bitmap bm;
try {
HttpResponse hr = hc.execute(hg);
bm = BitmapFactory.decodeStream(hr.getEntity().getContent());
} catch (Exception e) {
mHandler.obtainMessage(MSG_FAILURE).sendToTarget();//获取图片失败
return;
}
mHandler.obtainMessage(MSG_SUCCESS,bm).sendToTarget();//获取图片成功,向ui线程发送MSG_SUCCESS标识和bitmap对象
// mImageView.setImageBitmap(bm); //出错!不能在非ui线程操作ui元素
// mImageView.post(new Runnable() {//另外一种更简洁的发送消息给ui线程的方法。
//
// @Override
// public void run() {//run()方法会在ui线程执行
// mImageView.setImageBitmap(bm);
// }
// });
}
};
标签:android,主线程,子线程
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
spring schedule实现动态配置执行时间
2022-09-06 18:47:30
使用Spring组合自定义的注释 mscharhag操作
2023-02-14 11:18:01
JavaWeb登录界面登录失败在同一页面进行提示的解决
2023-11-26 15:51:34
![](https://img.aspxhome.com/file/2023/6/60356_0s.png)
C#中Socket通信用法实例详解
2022-07-10 03:42:03
Android TextView中文字通过SpannableString设置属性用法示例
2023-07-26 07:11:51
![](https://img.aspxhome.com/file/2023/8/84748_0s.jpg)
JAVA十大排序算法之快速排序详解
2022-06-08 16:09:11
![](https://img.aspxhome.com/file/2023/5/69315_0s.png)
Spring Cloud Gateway集成Sentinel流控详情
2023-11-09 20:27:31
![](https://img.aspxhome.com/file/2023/2/86812_0s.png)
springboot通过spel结合aop实现动态传参的案例
2022-01-26 01:00:47
![](https://img.aspxhome.com/file/2023/3/79883_0s.png)
判断一个整数是否是2的N次幂实现方法
2022-12-25 00:55:10
c#图片处理之图片裁剪成不规则图形
2023-02-23 02:43:58
![](https://img.aspxhome.com/file/2023/1/86981_0s.jpg)
Java 数据结构深入理解ArrayList与顺序表
2023-02-15 14:24:07
![](https://img.aspxhome.com/file/2023/1/62501_0s.png)
关于springBoot yml文件的list读取问题总结(亲测)
2023-11-04 12:37:08
![](https://img.aspxhome.com/file/2023/3/67443_0s.png)
快速理解Java垃圾回收和jvm中的stw
2021-09-06 20:27:17
Kotlin与Java的区别详解
2023-06-22 16:25:58
![](https://img.aspxhome.com/file/2023/6/75696_0s.jpg)
Java 数据结构与算法系列精讲之队列
2023-09-26 21:10:31
![](https://img.aspxhome.com/file/2023/7/80977_0s.gif)
Spring Security 中细化权限粒度的方法
2022-08-30 14:26:40
![](https://img.aspxhome.com/file/2023/8/83498_0s.png)
浅谈一下Java中的悲观锁和乐观锁
2023-08-12 05:54:27
Java实现分解任意输入数的质因数算法示例
2022-07-29 23:07:08
![](https://img.aspxhome.com/file/2023/9/69349_0s.jpg)
分析SpringBoot的启动原理
2021-10-30 16:01:23
![](https://img.aspxhome.com/file/2023/4/69324_0s.png)
Java使用Thread和Runnable的线程实现方法比较
2021-11-17 07:52:54