In Android, the handler method can be used to transmit data between threads. But do I have to pass the data obtained by handler to the main thread through loop and then update the UI? In fact, you can also directly use the post method designed by handler to implement the post method. The post method of handler runs in the main thread and can directly update the UI.
MainActivity code
package com.example.e15_handler_post;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import android.os.Bundle;import android.os.Handler;import android.app.Activity;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.util.Log;import android.view.Menu;import android.widget.ImageView;public class MainActivity extends Activity { private ImageView imageView; private Handler myhandler=new Handler();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);imageView=(ImageView)this.findViewById(R.id.imageView1);new MyThread().start();}@Overridepublic 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;}public class MyThread extends Thread{byte[] data=new byte[1024];int len=0;@Overridepublic void run() {// TODO Auto-generated method stub try {URL url=new URL("http://111.0.229.223:8080/http/hangzhou.jpg");try {HttpURLConnection connection=(HttpURLConnection) url.openConnection();InputStream inputStream=connection.getInputStream();ByteArrayOutputStream arrayOutputStream=new ByteArrayOutputStream();while((len=inputStream.read(data))!=-1){ arrayOutputStream.write(data, 0, len);}data=arrayOutputStream.toByteArray();Log.i("info", "------->"+data.length);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} Runnable runnable=new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubBitmap bm=BitmapFactory.decodeByteArray(data, 0,data.length );imageView.setImageBitmap(bm);}};myhandler.post(runnable);}}}