- Do not block the UI thread
- Do not access the Android UI toolkit from outside the UI thread
由第二點得知只能在UI Thread控制UI所以~~~Android提供了以下簡單方法:
這些方法可以讓你在另外一個執行緒控制UI
但是程式中過多這樣的寫法是不好的,於是發展了一個AsyncTask ,可將UI與背景想做的事分開,如此程式維護上比較清晰
要使用AsyncTask 必須Extends AsyncTask 做法如下:已下轉貼Android API低阿~
public void onClick(View v) { //你要執行時呼叫execute 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) { //這裡做在UI裡顯示什麼東西!如將網路抓來的圖片顯示在ImageView中 mImageView.setImageBitmap(result); } }
- 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 - You can cancel the task at any time, from any thread
沒有留言:
張貼留言