private class DownloadTask extends AsyncTask<String, Integer, Bitmap> {
Bitmap bitmap = null;
@Override
protected Bitmap doInBackground(String... params) {
try {
bitmap = downloadUrl(params[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
ImageView iView = (ImageView)findViewById(R.id.iv_image);
iView.setImageBitmap(result);
Toast.makeText(getBaseContext(), "Image downloaded successfully", Toast.LENGTH_LONG).show();
}
}
private Bitmap downloadUrl(String strUrl) throws IOException {
Bitmap bitmap = null;
InputStream iStream = null;
try {
URL url = new URL(strUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
bitmap = BitmapFactory.decodeStream(iStream);
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
}
return bitmap;
}
버튼 클릭 이벤트에서 다음을 호출한다.
@Override
public void onClick(View v) {
EditText etUrl = (EditText)findViewById(R.id.et_url);
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(etUrl.getText().toString());
}
매니페스트 파일에 인터넷을 사용할 수 있는 권한을 요청한다.(AndroidManifest.xml)
<uses-permission android:name="android.permission.INTERNET"/>