在Android中可以通过handler方法完成数据的线程间的传递,但一定要将handler得到的数据通过loop传递到主线程再更新UI吗?其实也可以直接使用handler设计的post方法进行实现,handler的post方法是在主线程运行的,可以直接进行UI的更新操作。
MainActivity的代码
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();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=(ImageView)this.findViewById(R.id.imageView1);
new MyThread().start();
}
@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;
}
public class MyThread extends Thread{
byte[] data=new byte[1024];
int len=0;
@Override
public 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 block
e.printStackTrace();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Runnable runnable=new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Bitmap bm=BitmapFactory.decodeByteArray(data, 0,data.length );
imageView.setImageBitmap(bm);
}
};
myhandler.post(runnable);
}
}
}