An important technique in Android Programming is to make potentially long task run asynchronously in your app, avoid blocking the UI thread, so your app feels more responsive. For example, downloading a file from the Internet, loading a media file from the external storage or applying a filter on an image bitmap etc. I will show you how to implement with AsyncTask, simple java threads and java Executor in Part 1.
Let’s say I want to load a bitmap from the internet, and set it to an ImageView , this might be what you’d write at first:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | //This is a terrible example, the UI thread is blocked when user click the button button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { //DON'T DO THIS!! URL url = new URL("https://www.google.com/images/logos/google_logo_41.png"); URLConnection conn = url.openConnection(); Bitmap bm = BitmapFactory.decodeStream(conn.getInputStream()); imageView.setImageBitmap(bm); } catch (Exception e) { Log.e(TAG, e.getMessage()); } } }); |
The Java way: simple Threads
You can implement it just like any other Java programs, define a Thread that does the job, and run it. Every Java programmer knows how to do that. Remember that if you want to modify the UI, you need to use runOnUiThread()