public void onClick(View v) { new DownloadImageTask().execute("http://example.com/image.png"); } private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { /** The system calls this to perform work in a worker thread and * delivers it the parameters given to AsyncTask.execute() */ protected Bitmap doInBackground(String... urls) { return loadImageFromNetwork(urls[0]); } /** The system calls this to perform work in the UI thread and delivers * the result from doInBackground() */ protected void onPostExecute(Bitmap result) { mImageView.setImageBitmap(result); } }
doInBackground()
在工作线程中自动执行;onPreExecute()
, onPostExecute()
, 和 onProgressUpdate()
在UI线程中执行。doInBackground()方法返回值被送往
onPostExecute()。
你可以在任何时间在doInBackground()
方法中调用publishProgress()方法,以在UI线程中执行
onProgressUpdate()
方法。Activity.runOnUiThread(Runnable)
View.post(Runnable)
View.postDelayed(Runnable, long)
调用 View.post(Runnable)
方法的代码实例如下:
public void onClick(View v) { new Thread(new Runnable() { public void run() { final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png"); mImageView.post(new Runnable() { public void run() { mImageView.setImageBitmap(bitmap); } }); } }).start(); }