package com.example.day_07asynctask; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.concurrent.ExecutionException; import android.os.AsyncTask; import android.os.Bundle; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; public class MainActivity extends Activity { private ImageView imageview; private ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageview = (ImageView) findViewById(R.id.imageview); progressBar = (ProgressBar) findViewById(R.id.progressBar); } public void button(View v){ AsyncTask asyncTask=new AsyncTask() { private Bitmap bitmap; @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); progressBar.setVisibility(View.VISIBLE); } @Override protected Bitmap doInBackground(URL... params) { try { String path="http://zxpic.gtimg.com/infonew/0/wechat_pics_-8590809.jpg/640"; URL url=new URL(path); HttpURLConnection openConnection = (HttpURLConnection) url.openConnection(); openConnection.setConnectTimeout(5000); openConnection.setRequestMethod("GET"); openConnection.setReadTimeout(5000); openConnection.connect(); if(200==openConnection.getResponseCode()){ InputStream inputStream = openConnection.getInputStream(); bitmap = BitmapFactory.decodeStream(inputStream); //返回 return bitmap; } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onPostExecute(Bitmap result) { // TODO Auto-generated method stub super.onPostExecute(result); imageview.setImageBitmap(bitmap); progressBar.setVisibility(View.GONE); } }; asyncTask.execute(); } }