惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

AI
AI
O
OpenAI News
Engineering at Meta
Engineering at Meta
F
Fortinet All Blogs
Jina AI
Jina AI
D
Docker
N
News and Events Feed by Topic
TaoSecurity Blog
TaoSecurity Blog
雷峰网
雷峰网
V
V2EX
小众软件
小众软件
N
News | PayPal Newsroom
GbyAI
GbyAI
Recorded Future
Recorded Future
SecWiki News
SecWiki News
WordPress大学
WordPress大学
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
酷 壳 – CoolShell
酷 壳 – CoolShell
Security Latest
Security Latest
Google DeepMind News
Google DeepMind News
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Hacker News: Ask HN
Hacker News: Ask HN
Project Zero
Project Zero
Cyberwarzone
Cyberwarzone
MyScale Blog
MyScale Blog
T
The Blog of Author Tim Ferriss
U
Unit 42
The Last Watchdog
The Last Watchdog
V
Visual Studio Blog
C
Cisco Blogs
T
Tor Project blog
Google Online Security Blog
Google Online Security Blog
I
InfoQ
Attack and Defense Labs
Attack and Defense Labs
Y
Y Combinator Blog
博客园 - 聂微东
L
LangChain Blog
Blog — PlanetScale
Blog — PlanetScale
Apple Machine Learning Research
Apple Machine Learning Research
S
Schneier on Security
S
Securelist
博客园_首页
W
WeLiveSecurity
P
Privacy International News Feed
S
SegmentFault 最新的问题
博客园 - 【当耐特】
L
LINUX DO - 热门话题
Latest news
Latest news
大猫的无限游戏
大猫的无限游戏
M
MIT News - Artificial intelligence

博客园 - 落叶潇潇雨

Can't get WebApplicationContext object from ContextRegistry.GetContext(): Resource handler for the 'web' protocol is not defined xml序列化与反序列化 Asp.net 导出Excel How to debug Typescript in browser log4net使用的关键点 DataContractSerializer序列化与反序列化遇到的奇怪问题 图文安装Windows Template Library - WTL Version 9.0 WCF的传输安全(读书笔记) Asp.net mvc 各个组件的分离 同程旅游网开放平台SDK开发完成 csdn回到顶端 SQL多行变一列 Timer的schedule和scheduleAtFixedRate方法的区别解析 activity生命周期 瀑布流插件 CSS自适应宽度圆角按钮 ajaxFileUpload上传文件和表单数据 Ajax上传表单数据和文件 使用Rhino Mocks
android 主线程和子线程之间的消息传递
落叶潇潇雨 · 2013-07-10 · via 博客园 - 落叶潇潇雨

从主线程发送消息到子线程(准确地说应该是非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);
//                }
//            });
        }
    };

}