Skip to content

Instantly share code, notes, and snippets.

@jsaund
Created September 20, 2016 05:31
Show Gist options
  • Save jsaund/bf4cfe5fbc5d32c71f785261e31b8761 to your computer and use it in GitHub Desktop.
Save jsaund/bf4cfe5fbc5d32c71f785261e31b8761 to your computer and use it in GitHub Desktop.
public class MainActivity extends AppCompatActivity {
private static final String IMAGE_URL = "https://www.android.com/static/img/android.png";
private static final int MSG_SHOW_PROGRESS = 1;
private static final int MSG_SHOW_IMAGE = 2;
private ProgressBar progressIndicator;
private ImageView imageView;
private Handler handler;
class ImageFetcher implements Runnable {
final String imageUrl;
ImageFetcher(String imageUrl) {
this.imageUrl = imageUrl;
}
@Override
public void run() {
handler.obtainMessage(MSG_SHOW_PROGRESS).sendToTarget();
InputStream is = null;
try {
// Download image over the network
URL url = new URL(imageUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
// Decode the byte payload into a bitmap
final Bitmap bitmap = BitmapFactory.decodeStream(is);
handler.obtainMessage(MSG_SHOW_IMAGE, bitmap).sendToTarget();
} catch (IOException ignore) {
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ignore) {
}
}
}
}
}
class UIHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_SHOW_PROGRESS: {
imageView.setVisibility(View.GONE);
progressIndicator.setVisibility(View.VISIBLE);
break;
}
case MSG_SHOW_IMAGE: {
progressIndicator.setVisibility(View.GONE);
imageView.setVisibility(View.VISIBLE);
imageView.setImageBitmap((Bitmap) msg.obj);
break;
}
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressIndicator = (ProgressBar) findViewById(R.id.progress);
imageView = (ImageView) findViewById(R.id.image);
handler = new UIHandler();
final Thread workerThread = new Thread(new ImageFetcher(IMAGE_URL));
workerThread.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment