主线程向子线程发送数据

时间:2021-01-19 18:28:11
package com.example.zjday18_handler_03;

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;
/**
* 主线程向子线程发送数据
* @author Administrator
*
*/

public class MainActivity extends Activity {

private Handler handler;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//开启子线程
new connectThread().start();
}

public void sendMessage(View v){
if(handler!=null){
Message msg =Message.obtain();
msg.obj ="向子线程中发送数据!";
handler.sendMessage(msg);
}
}

//子线程
class connectThread extends Thread{
@Override
public void run() {
//1.创建Looper对象
Looper.prepare();
//2.实例化Handler
handler =new Handler(){
public void handleMessage(Message msg) {
//接受主线程发送过来的消息
super.handleMessage(msg);
String info =(String) msg.obj;
Log.i("---", info);
};
};
//3.循环读取MessageQueue
Looper.loop();
}
}
}