① 實例化一個Handler並重寫handlerMessage()方法數組
private Handler handler = newHandler() { public void handleMessage(Message msg) { // 處理消息
super.handleMessage(msg); switch (msg.what) { case 1: button1.setText("點擊安裝"); break; case 2: button1.setText("打開"); break; } }; };
② 在子線程中獲取或建立消息,並使用handler對象發送ide
Message msg = handler.obtainMessage(); msg.what = 1; handler.sendMessage(msg);
runOnUiThread(new Runnable() { @Override public void run() { // 更新UI的操做
} });
myTextView.post(new Runnable() { @Override public void run() { // 更新UI
myView.setText(「更新UI」); }});
① 建立一個Handler成員變量post
private Handler handler = new Handler();
② 在子線程中調動post()方法url
handler.post(new Runnable() { @Override public void run() { // 更新UI
myView.setText(「更新UI」); }});
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long>
//在這裏聲明瞭Params、Progress、Result參數的類型
{ //由於這裏不須要使用onPreExecute回調方法,因此就沒有加入該方法 //後臺線程的目的是更具URL下載數據
protected Long doInBackground(URL... urls) { int count = urls.length;//urls是數組,不止一個下載連接
long totalSize = 0;//下載的數據
for (int i = 0; i < count; i++) { //Download是用於下載的一個類,和AsyncTask無關,你們能夠忽略他的實現
totalSize += Downloader.downloadFile(urls[i]); publishProgress((int) ((i / (float) count) * ));//更新下載的進度 // Escape early if cancel() is called
if (isCancelled()) break; } return totalSize; } //更新下載進度
protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]); } //將下載的數據更新到UI線程
protected void onPostExecute(Long result) { showDialog("Downloaded " + result + " bytes"); } }