android 线程间的通信

        在Android,线程分为有消息循环的线程和没有消息循环的线程,有消息循环的线程一般都会有一个Looper,这个是android 的新概念。我们的主线程(UI线程)就是一个消息循环的线程。针对这种消息循环的机制,我们引入一个新的机制Handler,我们有消息循环,就要往消息 循环里面发送相应的消息,自定义消息一般都会有自己对应的处理,消息的发送和清除,把这些都封装在Handler里面,注意Handler只是针对那些有 Looper的线程,不管是UI线程还是子线程,只要你有Looper,我就可以往你的消息队列里面添加东西,并做相应的处理。

  但是这里还有一点,就是只要是关于UI相关的东西,就不能放在子线程中,因为子线程是不能操作UI的,只能进行数据、系统等其他非UI的操作。

  一个Handler的创建它就会被绑定到这个线程的消息队列中,如果是在主线程创建的,那就不需要写代码来创建消息队列了,默认的消息队列会在 主线程被创建。但是如果是在子线程的话,就必须在创建Handler之前先初始化线程的消息队列。

        测试代码如下:

package com.example.android.hello;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Button;
import android.os.Looper;
import android.os.Message;
import java.lang.InterruptedException;


public class TestAndroid extends Activity {

    private static final String TAG = "MainThread";
    private Handler mMainHandler, mChildHandler;
    private TextView info;
    private Button msgBtn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        info = (TextView) findViewById(R.id.info);
        msgBtn = (Button) findViewById(R.id.msgBtn);

        mMainHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                Log.i(TAG, "Got an incoming message from the child thread - "
                + (String) msg.obj);
                // 接收子线程的消息
                info.setText((String) msg.obj);
            }
        };

        new ChildThread().start();

        msgBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (mChildHandler != null) {
                    // 发送消息给子线程
                    Message childMsg = mChildHandler.obtainMessage();

                    childMsg.obj = mMainHandler.getLooper().getThread()
                            .getName()
                            + " says Hello";
                    mChildHandler.sendMessage(childMsg);
                    Log.i(TAG, "Send a message to the child thread - "
                            + (String) childMsg.obj);
                }
            }
        });
    }

    public void onDestroy() {

        super.onDestroy();
        Log.i(TAG, "Stop looping the child thread's message queue");
        mChildHandler.getLooper().quit();
    }

    class ChildThread extends Thread {

        private static final String CHILD_TAG = "ChildThread";

        public void run() {
            this.setName("ChildThread");
            // 初始化消息循环队列,需要在Handler创建之前
            Looper.prepare();
            mChildHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    Log.i(CHILD_TAG,
                            "Got an incoming message from the main thread - "
                                    + (String) msg.obj);
                    Message toMain = mMainHandler.obtainMessage();
                    toMain.obj = "This is "
                            + this.getLooper().getThread().getName() +
                            ". Did you send me /"" + (String) msg.obj + "/"?";
                    mMainHandler.sendMessage(toMain);
                    Log.i(CHILD_TAG, "Send a message to the main thread - "
                            + (String) toMain.obj);
                }
            };
            Log.i(CHILD_TAG, "Child handler is bound to - "
                    + mChildHandler.getLooper().getThread().getName());
            // 启动子线程消息循环队列
            Looper.loop();
        }
    }
}


参考文章:http://cnmsdn.com/html/201008/1282525942ID7608.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android线程通信可以通过多种方式实现。其中一种常见的方式是使用Handler和Looper机制。通过在主线程中创建Handler对象,可以将消息发送到主线程的消息队列中,然后主线程的Looper会不断地从消息队列中取出消息并处理。在子线程中,可以通过Handler的post方法将消息发送到主线程。这样就实现了主线程和子线程通信。\[2\] 另外,如果需要在子线程进行通信,可以使用HandlerThread类。HandlerThread是一个带有Looper的线程,可以在其中创建Handler对象,并通过Handler发送消息到该线程的消息队列中。这样就可以实现子线程通信。\[3\] 总结起来,Android线程通信可以通过Handler和Looper机制实现主线程和子线程通信,也可以使用HandlerThread实现子线程通信。这些机制可以帮助开发者更好地处理多线程编程中的同步问题。\[1\] #### 引用[.reference_title] - *1* [Android线程通信原理以及多线程](https://blog.csdn.net/a734474820/article/details/125561136)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [【Android线程通信——Handler消息机制](https://blog.csdn.net/qq_40265247/article/details/123898141)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [android线程通信的几种方法_Android进程线程通信方式](https://blog.csdn.net/Goals1989/article/details/127966389)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值