AsyncTask使用

xiaoxiao2021-02-28  141

AsyncTask <Void,Inetger,Void> Params是指调用execute()方法时传入的参数类型和doInBackgound()的参数类型 Progress是指更新进度时传递的参数类型,即publishProgress()onProgressUpdate()的参数类型 Result是指doInBackground()的返回值类型 public class RequestAsyncTask extends AsyncTask<Long,Integer,String> { private Context context; private TextView tv; RequestAsyncTask(Context context,TextView tv) { this.context = context; this.tv = tv; } /** * 运行在UI线程中,在调用doInBackground()之前执行 */ @Override protected void onPreExecute() { Toast.makeText(context,"开始执行",Toast.LENGTH_SHORT).show(); } /** * 后台运行的方法,可以运行非UI线程,可以执行耗时的方法 */ @Override protected String doInBackground(Long... params) {// 对应AsyncTask 中的Long 泛型 int i=0; while(i<10){ i++; // publishProgress(i); try { Thread.sleep(1000); } catch (InterruptedException e) { } } return String.valueOf(i); // 返回onPostExecute()参数类型,对应AsyncTask 中的 String 泛型 } /** * 运行在ui线程中,在doInBackground()执行完毕后执行 */ @Override protected void onPostExecute(String integer) { Toast.makeText(context,"执行完毕+"+integer,Toast.LENGTH_SHORT).show(); } /** * 在publishProgress()被调用以后执行,publishProgress()用于更新进度 */ @Override protected void onProgressUpdate(Integer... values) { tv.setText(""+values[0]); } }
转载请注明原文地址: https://www.6miu.com/read-17773.html

最新回复(0)