AsyncTask使用解析

AsyncTask主要用來更新UI線程,比較耗時的操做能夠在AsyncTask中使用。
AsyncTask是一個抽象類,使用時須要繼承這個類,而後調用execute()方法開始執行異步任務。異步

Async有三個泛型參數Async<params,inetger,result>:
  • Params是指調用execute()方法時傳入的參數類型和doInBackground()的參數類型
  • Progress是指更新進度時傳遞的參數類型,即publishProgress()和onProgressUpdate()的參數類型
  • Result是指doInBackground()的返回值類型

上面的說明涉及到幾個方法:async

  • doInBackgound() 這個方法是繼承AsyncTask必需要實現的,
    運行於後臺,耗時的操做能夠在這裏作
  • publishProgress() 更新進度,給onProgressUpdate()傳遞進度參數
  • onProgressUpdate() 在publishProgress()調用完被調用,更新進度

實際的例子:

  1. publicclassMyActivityextendsActivity
  2. {
  3. privateButton btn;
  4. privateTextView tv;
  5. @Override
  6. publicvoid onCreate(Bundle savedInstanceState)
  7. {
  8. super.onCreate(savedInstanceState);
  9. setContentView(R.layout.main);
  10. btn =(Button) findViewById(R.id.start_btn);
  11. tv =(TextView) findViewById(R.id.content);
  12. btn.setOnClickListener(newButton.OnClickListener(){
  13. publicvoid onClick(View v){
  14. update();
  15. }
  16. });
  17. }
  18. privatevoid update(){
  19. UpdateTextTask updateTextTask =newUpdateTextTask(this);
  20. updateTextTask.execute();
  21. }
  22. classUpdateTextTaskextendsAsyncTask<Void,Integer,Integer>{
  23. privateContext context;
  24. UpdateTextTask(Context context){
  25. this.context = context;
  26. }
  27. /**
  28. * 運行在UI線程中,在調用doInBackground()以前執行
  29. */
  30. @Override
  31. protectedvoid onPreExecute(){
  32. Toast.makeText(context,"開始執行",Toast.LENGTH_SHORT).show();
  33. }
  34. /**
  35. * 後臺運行的方法,能夠運行非UI線程,能夠執行耗時的方法
  36. */
  37. @Override
  38. protectedInteger doInBackground(Void... params){
  39. int i=0;
  40. while(i<10){
  41. i++;
  42. publishProgress(i);
  43. try{
  44. Thread.sleep(1000);
  45. }catch(InterruptedException e){
  46. }
  47. }
  48. returnnull;
  49. }
  50. /**
  51. * 運行在ui線程中,在doInBackground()執行完畢後執行
  52. */
  53. @Override
  54. protectedvoid onPostExecute(Integer integer){
  55. Toast.makeText(context,"執行完畢",Toast.LENGTH_SHORT).show();
  56. }
  57. /**
  58. * 在publishProgress()被調用之後執行,publishProgress()用於更新進度
  59. */
  60. @Override
  61. protectedvoid onProgressUpdate(Integer... values){
  62. tv.setText(""+values[0]);
  63. }
  64. }
  65. }



相關文章
相關標籤/搜索