//首先呢,添加网络权限
android.permission.INTERNET
//然后,布局View
img=(Image)findViewById(R.id.imageView1);
btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String path=”网络图片路径”;
new DemoTask().execute(path);
}
});
//最后:创建一个类继承AsyncTask
public class DemoTask extends AsyncTask(String, Void, Bitmap){
//重写doInBackground来进行任务
protected Bitmap doInBackground(String… params){
HttpClient httpClient = new DefaultHtppClient();
HttpGet httpGet = new HttpGet(params[0]);
Bitmap bitmap=null;
try{
HttpResponse httpResponse = httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode==200){
//同样,在这里可以获取到很多东西
//例如输入流:inputStream=httpResponse.getEntity().getContent();
HttpEntity httpEntity = HttpResponse.getEntity();
byte [] data = EntityUtils.toByteArray(httpEntity);
bitmap=BitmapFactory.decodeByteArray(data, 0, data.length);
}
}catch(Exception e){
e.printStackTrace();
}
return bitmpa;
}
//重写onPostExecute来更新View
protected void onPostExecute(Bitmap bm){
super.onPostExecute(result);
img.setImageBitmap(bm);
}
}