Android笔记(子线程通过Handler修改UI)
2015-09-12
线程
MainThread与WorkerThread
WorkerThread里面一般不允许修改UI,而在MainThread里面又不宜进行可能产生阻塞的操作,所以会产生MainThread和WorkerThread通信的问题,就出现handler,looper来解决此问题
2015-09-13
什么是Handler
Handler,Looper(循环器)和MessageQueue的基本原理
Message(消息)------------>(通过Handler放入)------------>【消息队列】--------->(Looper取出消息)
2015-09-14
由于WorkerThread一般不允许修改UI,所以要新建Handler内部类,在WorkerThread里面调用handler方法,获取网络数据;在Handler里用handleMessage方法修改textView,在主线程中新建Handler对象.(handler就相当于一个中间工具,实现把子线程的数据传到主线程)
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.textView);
button = (Button)findViewById(R.id.button);
handler = new MyHandler();
button.setOnClickListener(new ButtonListener());
}
@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;
}
class ButtonListener implements OnClickListener{
@Override
public void onClick(View arg0) {
Thread thread = new NetworkThread();
thread.start();
}
}
class MyHandler extends Handler{
@Override
public void handleMessage(Message msg) {
String s =(String)msg.obj;
textView.setText(s);
}
}
class NetworkThread extends Thread{
@Override
public void run() {
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String s = "从网络中获取数据";
Message msg = handler.obtainMessage();
msg.obj = s;
handler.sendMessage(msg);
}
}