您的位置 首页 应用

android 线程通讯

activity_main.xmlxmlns:tools=http://schemas.android.com/toolsandroid:layout_width=match_parentandroi

activity_main.xml

xmlns:tools=http://schemas.android.com/tools

android:layout_width=match_parent

android:layout_height=match_parent

android:paddingBottom=@dimen/activity_vertical_margin

android:paddingLeft=@dimen/activity_horizontal_margin

android:paddingRight=@dimen/activity_horizontal_margin

android:paddingTop=@dimen/activity_vertical_margin

tools:context=.MainActivity >

android:id=@+id/button1

android:layout_width=wrap_content

android:layout_height=wrap_content

android:layout_alignParentLeft=true

android:layout_alignParentTop=true

android:layout_marginTop=16dp

android:text=通讯 />

MainActivity.java

public class MainActivity extends Activity implements OnClickListener{

Handler mainHanler,subHandler;

Button btn1;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

initViews();

mainHanler = new Handler(){

@Override

public void handleMessage(Message msg) {

super.handleMessage(msg);

if(msg.what == 1){

System.out.println(msg.obj.toString());

}

}

};

new WorkThread().start();

}

public void initViews(){

btn1 = (Button) findViewById(R.id.button1);

btn1.setOnClickListener(this);

}

@Override

public void onClick(View v) {

switch (v.getId()) {

case R.id.button1:

//交互

Message msg = Message.obtain();

msg.what = 1;

msg.obj = 儿子,哥来看你啦!;

subHandler.sendMessage(msg);

break;

}

}

public class WorkThread extends Thread{

@Override

public void run() {

Looper.prepare();

subHandler = new Handler(){

@Override

public void handleMessage(Message msg) {

if(msg.what == 1){

//承受音讯

System.out.println(msg.obj.toString());

}

//发音讯给主线程

Message m = Message.obtain();

m.what = 1;

m.obj = 老爸我来啦!;

mainHanler.sendMessage(m);

}

};

Looper.loop();

}

}

}

声明:本文内容来自网络转载或用户投稿,文章版权归原作者和原出处所有。文中观点,不代表本站立场。若有侵权请联系本站删除(kf@86ic.com)https://www.86ic.net/yingyong/297363.html

为您推荐

联系我们

联系我们

在线咨询: QQ交谈

邮箱: kf@86ic.com

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部