3

我正在使用以下功能从服务器下载图像。这适用于除 Android 2.2 Froyo 设备之外的所有 android 版本。请帮忙。

    private Bitmap downloadImage(String url) {
        System.out.println("Splash Ad downloadImage Url " + url);
        Bitmap bm = null;
        try {
            URL aURL = new URL(url);
            URLConnection conn = aURL.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();
        } catch (IOException e) {
            Log.e("Hub", "Error getting the image from server : "
                    + e.getMessage().toString());
            e.printStackTrace();
        }
        return bm;
    }
4

1 回答 1

0

试试这个代码。

public class ImageDisplay extends Activity {
         ImageView image;
         ProgressBar spinner;
         TextView message;
         String path;
@Override
      public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_image_display);
    image=(ImageView) findViewById(R.id.imageDisplay);
    spinner=(ProgressBar)findViewById(R.id.progressBar_spinner);
    message=(TextView)findViewById(R.id.textView1);
    spinner.setVisibility(View.INVISIBLE);
   displayImage();
}
       private class DownloadImage extends AsyncTask<String, Void,Bitmap >
             {
Bitmap bitmap;
String error_messsage="No error";
@Override
protected Bitmap  doInBackground(String... urls) {
    for(String url:urls){
     HttpUriRequest request = new HttpGet(url.toString());
        HttpClient httpClient = new DefaultHttpClient();
        try {
            HttpResponse response = httpClient.execute(request);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
              HttpEntity entity = response.getEntity();
              byte[] bytes = EntityUtils.toByteArray(entity);
          Log.e("here",""+bytes.length); 
              bitmap = BitmapFactory.decodeByteArray(bytes, 0,bytes.length);
              Thread.sleep(1000);
            }
            else
            {
                error_messsage="Download failed, HTTP response code "+ statusCode + " - " + statusLine.getReasonPhrase();                   
            }
        } catch (Exception er) {
            Log.e("Error",""+er);
        }}
        //image.setImageBitmap(bitmap);
    return bitmap ;
}

@Override
protected void onPostExecute(Bitmap result) {
    spinner.setVisibility(View.INVISIBLE);
    image.setImageBitmap(result);

}
    }
     public void displayImage()
    {

   DownloadImage task = new DownloadImage();   
   task.execute(new String[] { "http://team-android.com/wp-             content/uploads/2011/03/Android-3d_428.jpg" });
   snap.setVisibility(View.VISIBLE);

    }
于 2012-12-24T09:19:53.803 回答