通常情况下,使用Handler是子线程向主线程发送数据,今天复习Handler,思考怎么主线程向子线程发送数据,进过测试没有问题。
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 gavin
*
*/
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();
}
}
}