-
FirstAcitvity
public class FirstActivity extends AppCompatActivity {
private Button but = null;
private static final int SET = 1; //what操作碼
private TextView info = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_main);
this.info = (TextView)findViewById(R.id.info);
this.but = (Button)findViewById(R.id.but);
this.but.setOnClickListener(new OnClickListenterImpl());
}
private class OnClickListenterImpl implements View.OnClickListener {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.but:
Looper looper = Looper.myLooper(); //取得當前線程
MyHandler myHandler = new MyHandler(looper); //構造一個handler
myHandler.removeMessages(0); //清空所有的消息隊列
String data = "hello,world";
Message msg = myHandler.obtainMessage(SET,1,1,data); //發送消息
myHandler.sendMessage(msg);
break;
}
}
}
private class MyHandler extends android.os.Handler {
public MyHandler(Looper looper) { //接收handler
super(looper); //調用父類構造
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
FirstActivity.this.info.setText(msg.obj.toString());
}
}
}
}
2. activity_main.xml<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/info"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/but"
android:text="啓動"
android:layout_below="@+id/info"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="76dp" />