AsyncTask非同步任務類使用

2021-07-14 10:39:27 字數 1825 閱讀 5794

優點:封裝了handler+thread+執行緒池

特點:1

、android

中已經寫好了的多執行緒

2、處理

ui thread

和worker 

**示例:

kateasyctask task = new kateasyctask();

task.execute(url,1+"");

class kateasyctask extends asynctask

/***/

@override

protected bitmap doinbackground(string... params)

bitmap = bitmapfactory.decodefile(sd_card_path+"/"+filename);

}} catch (exception e) finally

if(inputstream!=null)

} catch (ioexception e)

}return bitmap;

}/**

*/@override

protected void onprogressupdate(integer... values)

/*** 在主線程中執行:接收非同步執行緒返回的結果

*/@override

protected void onpostexecute(bitmap result)

/*** 取消非同步任務(終止)

*/@override

protected void oncancelled()

}

asynctask執行非同步任務的原始碼分析

1, public asynctask()

初始化了 mworker(runnable)  mfuture(task)

2, task.execute(params... params)

executeonexecutor(sdefaultexecutor, params);

onpreexecute();

exec.execute(mfuture);

sdefaultexecutor.execute(mfuture);

serialexecutor.execute(mfuture);

mfuture(mworker).run();

callback.call();

mworker.call();

doinbackground(mparams)

postresult

通過handler傳送訊息:message_post_result

3,internalhandler extends handler

message_post_result:

onpostexecute(result);

message_post_progress

onprogressupdate(result.mdata);

4,  publishprogress(progress... values)

shandler.obtainmessage(message_post_progress,

new asynctaskresult(this, values)).sendtotarget();

5, 通過執行緒工廠來 建立執行緒 :

threadfactory sthreadfactory = new threadfactory()

AsyncTask非同步任務

asynctask非同步任務怎麼寫 寫乙個類繼承asynctask,重寫方法 doinbackgroud 再new 這個類,執行物件 execute 在ui執行緒裡面寫這個類的實現方法 doinbackground有可能是新開的執行緒,有可能是執行緒池裡面的執行緒 執行順序 onpreexecute...

非同步任務(AsyncTask)

一 解決新執行緒無法更新ui組建問題的方案 為了解決新執行緒不能更新ui組建的問題,andorid提供了如下幾種解決方案 1.使用handler實現執行緒之間的通訊。mhandler new handler public class mythread extends thread 2.activit...

非同步任務AsyncTask

強調!以下只是我個人看法,如有錯誤的地方請文明指出 為避免主線程失去響應問題,android建議將耗時操作放在新的執行緒中,但是新的執行緒可能需要動態的更新ui元件,比如需要從網上獲取乙個網頁,讓後在textview上將其源 顯示出來,此時就要連線網路 獲取網路資料的操作放在新執行緒中完成。問題是獲...