[Android]异步任务AsyncTask使用解析

AsyncTask主要用来更新UI线程,比较耗时的操作可以在AsyncTask中使用。

AsyncTask是个抽象类,使用时需要继承这个类,然后调用execute()方法。注意继承时需要设定三个泛型Params,Progress和Result的类型,如AsyncTask<Void,Inetger,Void>:

  • Params是指调用execute()方法时传入的参数类型和doInBackgound()的参数类型
  • Progress是指更新进度时传递的参数类型,即publishProgress()和onProgressUpdate()的参数类型
  • Result是指doInBackground()的返回值类型
上面的说明涉及到几个方法:
  • doInBackgound() 这个方法是继承AsyncTask必须要实现的,运行于后台,耗时的操作可以在这里做
  • publishProgress() 更新进度,给onProgressUpdate()传递进度参数
  • onProgressUpdate() 在publishProgress()调用完被调用,更新进度
好了,看下实际的例子,了解一下怎么使用吧:
  1. publicclassMyActivityextendsActivity
  2. {
  3. privateButtonbtn;
  4. privateTextViewtv;
  5. @Override
  6. publicvoidonCreate(BundlesavedInstanceState)
  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. publicvoidonClick(Viewv){
  14. update();
  15. }
  16. });
  17. }
  18. privatevoidupdate(){
  19. UpdateTextTaskupdateTextTask=newUpdateTextTask(this);
  20. updateTextTask.execute();
  21. }
  22. classUpdateTextTaskextendsAsyncTask<Void,Integer,Integer>{
  23. privateContextcontext;
  24. UpdateTextTask(Contextcontext){
  25. this.context=context;
  26. }
  27. /**
  28. *运行在UI线程中,在调用doInBackground()之前执行
  29. */
  30. @Override
  31. protectedvoidonPreExecute(){
  32. Toast.makeText(context,"开始执行",Toast.LENGTH_SHORT).show();
  33. }
  34. /**
  35. *后台运行的方法,可以运行非UI线程,可以执行耗时的方法
  36. */
  37. @Override
  38. protectedIntegerdoInBackground(Void...params){
  39. inti=0;
  40. while(i<10){
  41. i++;
  42. publishProgress(i);
  43. try{
  44. Thread.sleep(1000);
  45. }catch(InterruptedExceptione){
  46. }
  47. }
  48. returnnull;
  49. }
  50. /**
  51. *运行在ui线程中,在doInBackground()执行完毕后执行
  52. */
  53. @Override
  54. protectedvoidonPostExecute(Integerinteger){
  55. Toast.makeText(context,"执行完毕",Toast.LENGTH_SHORT).show();
  56. }
  57. /**
  58. *在publishProgress()被调用以后执行,publishProgress()用于更新进度
  59. */
  60. @Override
  61. protectedvoidonProgressUpdate(Integer...values){
  62. tv.setText(""+values[0]);
  63. }
  64. }
  65. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值