package com.apofa.httpAccess; import java.io.BufferedInputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; public class httpAccess extends Activity { /** Called when the activity is first created. */ ImageView displayView; Button downloadImage; Bitmap bm; String imageurl = "http://www.leckerfett.com/napf/andesk.png"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); downloadImage= (Button)findViewById(R.id.getimage); displayView = (ImageView)findViewById(R.id.imageview); downloadImage.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { //this would do in same thread and mean you //have to wait for image - couldn't type in //text field...running on same thread as this activity //displayImage(downloadImage(imageurl)); //This uses Downloader class that runs the downloading //in a different thread giving back control to this //activity so can type in text field. //see definition of inside class Downloader below Downloader dm= new Downloader(); dm.execute(imageurl); //triggers dm.doInbackground //when this is done will then //call dm.onPostExecute of the } }); } public void displayImage(Bitmap bm){ BitmapDrawable bmdw = new BitmapDrawable(bm); displayView.setBackgroundDrawable(bmdw); } public Bitmap downloadImage(String url){ try{ URL aURL = new URL(url); URLConnection conn = aURL.openConnection(); conn.connect(); //Log.d("LOADIMAGE","GET STREAM "); InputStream is = conn.getInputStream(); //Log.d("LOADIMAGE","BUFFER STREAM"); /* Buffered is always good for a performance plus. */ BufferedInputStream bis = new BufferedInputStream(is); Bitmap bm = BitmapFactory.decodeStream(bis); return bm; } catch(Exception e){ Log.d("httpAccess", "message:"+e.toString()); return null; } } //uses workingThread--via AsyncTask // param1 =type of pass in value ,param2= type of progress unit (how much done), param3=type returned private class Downloader extends AsyncTask { //this method will be run in separate thread in background protected Bitmap doInBackground(String... searchKey) { //String... means multiple parameters of String type...i.e. url1,url2,url3 String url = searchKey[0]; try{ Log.v("gsearch","gsearch result with AsyncTask"); return downloadImage(url); //calling now from this new working thread }catch(Exception e){ Log.v("Exception google search","Exception:"+e.getMessage()); return null; } } protected void onPostExecute(Bitmap resultbm) { try{ displayImage(resultbm); }catch(Exception e){ Log.v("Exception google search","Exception:"+e.getMessage()); } } } }