用ThreadHandle可以实现多线程,然后再主线程更新UI
第二种就是用
AsyncTask
具体看代码
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(),这个函数返回的值就是onPostExcute里面的参数
具体看如下官方文档
You should read the AsyncTask
reference for a full understanding on how to use this class, but here is a quick overview of how it works:
- You can specify the type of the parameters, the progress values, and the final value of the task, using generics
- The method
doInBackground()
executes automatically on a worker thread onPreExecute()
,onPostExecute()
, andonProgressUpdate()
are all invoked on the UI thread- The value returned by
doInBackground()
is sent toonPostExecute()
- You can call
publishProgress()
at anytime indoInBackground()
to executeonProgressUpdate()
on the UI thread