AsyncTask的参数分析

本文深入探讨了AsyncTask的使用方法,详细解释了三个泛型参数的作用,包括Params、Progress和Result,并通过实例展示了如何在UI线程前预执行任务,后台线程执行计算操作,以及UI线程后的执行操作。同时,阐述了如何在执行过程中发布进度更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AsyncTask的使用:

new MyTask().execute(Params...params);
AsyncTask的三个泛型参数说明(三个参数可以是任何类型)
1. 第一个参数Params:传入doInBackground()方法的参数类型
2. 第二个参数Progress:传入onProgressUpdate()方法的参数类型
3. 第三个参数Result:传入onPostExecute()方法的参数类型,也是doInBackground()方法返回的类型

private class MyTask extends AsyncTask<Params, Progress, Result> {
    
    /*
     * Runs on the UI thread before doInBackground(Params...)
     */
    protected void onPreExecute (){
        ...
    }
    
/*
 * Override this method to perform a computation on a background thread. 
 * The specified parameters are the parameters passed to execute(Params...)
 * by the caller of this task.This method can call publishProgress(Progress...)
 * to publish updates on the UI thread.
 */
    protected Result doInBackground (Params... params){
        ...
    }
    
/*
 * Runs on the UI thread after doInBackground(Params...). 
 * The specified result is the value returned by doInBackground(Params...).
 * This method won't be invoked if the task was cancelled.
 * Parameters result:The result of the operation computed by doInBackground(Params...).
 */
    protected void onPostExecute (Result result){
        ...
    }
    
/*
 * Runs on the UI thread after publishProgress(Progress...) is invoked. 
 * The specified values are the values passed to publishProgress(Progress...).
 */
    protected void onProgressUpdate (Progress... values) {
        ...
    }
    
 /*
  * This method can be invoked from doInBackground(Params...) to publish updates
  * on the UI thread while the background computation is still running. 
  * Each call to this method will trigger the execution of 
  * onProgressUpdate(Progress...) on the UI thread. onProgressUpdate(Progress...)
  *  will not be called if the task has been canceled.
  */
    protected final void publishProgress (Progress... values) {
        ...
    }
   
/* 
 * Runs on the UI thread after cancel(boolean) is invoked and doInBackground(Object[])
 *  has finished.The default implementation simply invokes onCancelled()
 *  and ignores the result.If you write your own implementation, 
 *  do not call super.onCancelled(result).
 */
    protected void onCancelled (Result result) {
       ...
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值