您的位置:首页 > 移动开发 > Android开发

Android开发之Handler(2)

2016-05-16 19:22 453 查看
WorkThread发送消息,在MainThread中接受消息,并且利用该消息处理UI。
<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/textViewId" 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/textViewId" android:text="发送消息" /></RelativeLayout>

MainActivity.javapackage com.example.handlernew1;import android.app.Activity;import android.graphics.MaskFilter;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 TextView textView; private Button button; private Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView)findViewById(R.id.textViewId); button = (Button)findViewById(R.id.buttonId); handler = new MyHandler(); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { Thread t=new NetworkThread(); t.start(); } }); } class MyHandler extends Handler{ @Override public void handleMessage(Message msg) { System.out.println("handleMessage-------->"+Thread.currentThread().getName()); String s= (String)msg.obj; textView.setText(s); } } class NetworkThread extends Thread{
@Override public void run() { System.out.println("networkthread-------->"+Thread.currentThread().getName()); // 模拟访问网络,当线程运行时,首先休眠两分钟 try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } String s="从网络中获取的数据"; Message msg=new Message(); msg.obj = s; //sendMessage()方法,无论是在主线程还是在Worker Thread当中,都是可以的。 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; }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: