可以通过异步加载来访问和显示服务器上的图片
代码其实也很简单
ImageActivity:
package com.example.httpapp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class ImageActivity extends Activity {
private Button get;
private ImageView ima;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
get=(Button) findViewById(R.id.get);
ima=(ImageView) findViewById(R.id.ima);
get.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//使用异步加载来设置图片
AsynctaskImage asy=new AsynctaskImage(ima);
asy.execute(new String[]{"http://192.168.56.1:8088/upload/12369675977831078_490x490.jpg"});
}
});
}
}
布局文件就不贴了,代码很简单,就一个Button和ImageView
AsynctaskImage:
/*
* 3个泛型
* 第一个是后台处理时需要传递过来的数据类型,比如URL---String
* 第二个是进度百分比
* 第三个是后台处理完所返回的数据类型
*/
public class AsynctaskImage extends AsyncTask<String, Integer, Bitmap>{
private ImageView img;
public AsynctaskImage(ImageView img){
this.img=img;
}
//后台执行,写入操作比较耗时的动作(访问图片),所以不能执行UI更新,这里String对应第一种泛型
@Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
//访问图片
//更具URL找到图片资源
try {
URL url=new URL("http://192.168.56.1:8088/upload/12369675977831078_490x490.jpg");
InputStream is=url.openStream();
//为了防止图片过大,造成内存溢出的问题,缩小图片
BitmapFactory.Options option=new BitmapFactory.Options();
option.inSampleSize=2;
Bitmap bitmap=BitmapFactory.decodeStream(is,null,option);
return bitmap;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//相当于Handler处理Ui的方法,在这里可以使用doInBackground得到返回的结果,
//这个方法是在主线程执行,任务执行的结果做为此方法的参数返回,这里的Bitmap参数对应第三个泛型,
//也就是接受doInBackground的返回值
@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
if(img!=null&&result!=null){
img.setImageBitmap(result);
}
super.onPostExecute(result);
}
}