现在的位置: 首页 > 综合 > 正文

android多线程1

2017年11月18日 ⁄ 综合 ⁄ 共 2623字 ⁄ 字号 评论关闭

主线程有默认的消息队列。子线程需要创建自己的消息队列。有了消息队列才可以发消息,处理消息。

public class MainActivity extends Activity {

 

private Button btn=null;

private TextView tv=null;

private  MyHandler myHandler=null;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

//获得和当前线程关联的Looper实例

Looper looper=Looper.myLooper();

 myHandlernew MyHandler(looper);

btn=(Button)this.findViewById(R.id.button1);

tv=(TextView)this.findViewById(R.id.textView1);

btn.setOnClickListener(new OnClickListener(){

 

@Override

public void onClick(View arg0) {

//启动线程

(new MyThread()).start();

}

});

}

 

public class MyThread extends Thread{

 

@Override

public void run() {

Message msg=Message.obtain();

msg.arg1=100;

msg.arg2=200;

msg.obj="android and java";

myHandler.sendMessage(msg);

super.run();

}

}

//定义一个Handler子类处理子线程

public class MyHandler extends Handler{

public MyHandler(){

}

//looper管理与之匹配的线程

public MyHandler(Looper looper)

{

super(looper);

}

@Override

public void handleMessage(Message msg) {

super.handleMessage(msg);

Log.i("<<<arg1<<<", msg.arg1+"");

Log.i("<<<arg2<<<", msg.arg2+"");

Log.i("<<<obj<<<", msg.obj+"");

tv.setText( msg.obj+"");

}

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.main, menu);

return true;

}

 

}

 

 

 

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

子线程接收消息并处理数据

Handler来管理消息队列,Looper来管理Handler,使得其能够运行起来

 

public class MainActivity extends Activity {

 

private Button btn=null;

private TextView tv=null;

private  Handler handler=null;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

//启动线程

(new MyThread()).start();

btn=(Button)this.findViewById(R.id.button1);

tv=(TextView)this.findViewById(R.id.textView1);

btn.setOnClickListener(new OnClickListener(){

 

@Override

public void onClick(View arg0) {

//主线程发消息

Message msg=Message.obtain();

msg.arg1=100;

msg.arg2=200;

msg.obj="android and java";

handler.sendMessage(msg);

}

});

}

//子线程来处理消息

public class MyThread extends Thread{

 

@Override

public void run() {

//Initialize the current thread as a looper. This gives you a chance to create handlers that then reference 

Looper.prepare();//循环消息队列

//接收并处理数据

handler=new Handler(){

 

@Override

public void handleMessage(Message msg) {

Log.i("<<<<<arg1<<<", msg.arg1+"");

Log.i("<<<<<arg2<<<", msg.arg2+"");

Log.i("<<<<<obj<<<", msg.obj+"");

//tv.setText(msg.obj+"");

super.handleMessage(msg);

}

};

//Run the message queue in this thread

Looper.loop();//直到消息队列循环结束

super.run();

}

}

 

}

 

 

【上篇】
【下篇】

抱歉!评论已关闭.