package com.njulya.testhandler; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { private Handler handler; private TextView text ; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text = (TextView)findViewById(R.id.textId); button = (Button)findViewById(R.id.buttonId); button.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { NetworkThread nt = new NetworkThread(); nt.start(); } }); handler = new Handler(){ @Override public void handleMessage(Message msg){ String str = (String)msg.obj; text.setText(str); } }; } private class NetworkThread extends Thread{ @Override public void run(){ try { sleep(2*1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } Message msg = handler.obtainMessage(); msg.obj = "从网络获得的数据"; handler.sendMessage(msg); } } @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; } }
<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=".MainActivity" > <TextView android:id="@+id/textId" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> <Button android:id="@+id/buttonId" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/textId" android:text="数据"/> </RelativeLayout>
Android专题3——MainThread向WorkerThread通信
原文:http://www.cnblogs.com/lya-nju/p/4190087.html