标签:
package com.example.looper; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { private Button send; private Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); send = (Button) findViewById(R.id.button1); new Thread(new MyThread()).start(); //主线程有一个默认的Looper send.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Message message = Message.obtain(); message.obj = "Jackson"; handler.sendMessage(message); } }); } public class MyThread implements Runnable{ @Override public void run() { //在子线程没有Looper的概念 Looper.prepare();//循环消息队列 //在子线程实例化handler handler = new Handler(){ @Override public void handleMessage(Message msg) { //子线程中接收主线程发送过来的消息 super.handleMessage(msg); System.out.println("--从主线程获取消息-->>" + msg.obj); } }; Looper.loop(); } } }
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 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="com.example.looper.MainActivity" > <Button android:id="@+id/button1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="56dp" android:text="发送消息" /> </RelativeLayout>
在Logcat下查看输出的结果
标签:
原文地址:http://blog.csdn.net/lindonglian/article/details/43316599