From ModMyGPhone Wiki
This is a simple Activity to demonstrate use of HttpUrlConnection class to download an image and display it.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageBtn = (Button) findViewById(R.id.imgbt);
imageBtn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
pd = ProgressDialog.show(ImgDwnld.this, "Downloading Image", "Please Wait..", false);
Thread one = new Thread()
{
public void run()
{
getFile(Url);
mHandler.post(mUpdateResults);
}
};
one.start();
}
});
image = (ImageView) findViewById(R.id.image);
}
- Network syncing should never take place in the main UI thread, hence we create a new thread to download data.
- Ideally, the user should be able to continue using the app while the data is being downloaded in background, but since here we have nothing else to do, there is no harm in putting up a ProgressDialog.
- mHandler is used to update the main UI thread once we are done with downloading.
void getFile(String fileurl)
{
URL myUrl = null;
try
{
myUrl = new URL(fileurl);
} catch (MalformedURLException e)
{
e.printStackTrace();
}
try
{
HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
bmp = BitmapFactory.decodeStream(is);
} catch (IOException e)
{
e.printStackTrace();
}
}
- myUrl holds the URL that we declared as a String earlier.
- HttpUrlConnection manages the HTTP connections.
- Connection object conn is created by invoking openConnection() on myUrl.
- Actual connection to the remote object is made using connect().
- InputStream is reads the incoming data and is decoded into a bitmap by decodeStream().
final Runnable mUpdateResults = new Runnable()
{
public void run()
{
pd.dismiss();
image.setImageBitmap(bmp);
imageBtn.setVisibility(View.INVISIBLE);
}
};
- As explained earlier, when the downloading completes, call is made to Runnable object mUpdateResults to update the UI thread.
_______________
Download Source
_______________