zoukankan      html  css  js  c++  java
  • AsyncTask

    AsyncTask的基本用法

    步骤

    1. 创建一个内部类继承AsyncTask<Params, Progress, Result>

       class MyTask extends AsyncTask<Void, Integer, String>
      
      • Params继承Object,用于设置doInBackground的形参。
      • Progress继承Object,用于设置onProgressUpdate的形参。
      • Result继承Object,用于设置onPostExecute的形参以及doInBackground的返回值。
    2. 重写其中的onPreExecute,doInBackground,onProgressUpdate,onPostExecute,onCancelled方法。

       @Override
       //初始化AsyncTask
       protected void onPreExecute() {
           super.onPreExecute();
       }
       @Override
       //将数据通过publishProgress(Progress...values)传输给onPostExectue
       //并且将返回值传给onPostExecute
       protected String doInBackground(Void... voids) {
       	return null;
       }
       @Override
       //接受publishProgress(Progress...values)传递过来的值
       //values是一个数组,一般取值用values[0]
       protected void onProgressUpdate(Integer... values) {
           super.onProgressUpdate(values);
       }
       @Override
       //执行完毕时调用的方法
       protected void onPostExecute(String s) {
           super.onPostExecute(s);
       }
       @Override
       //销毁AsyncTask时调用的方法
       protected void onCancelled() {
           super.onCancelled();
       }
      
    3. 创建一个MyTask并执行execute方法

       MyTask task = new MyTask();
       task.execute();
      

    相关代码

    关于AsyncTask基本应用的DEMO

  • 相关阅读:
    344.反正字符串
    125.验证回文串
    167.两数之和 II
    278.第一个错误的版本
    缓冲流
    Windows10剪贴板不能用
    chapter_21【字节流、字符流】
    属性集
    IO异常的处理
    字符流
  • 原文地址:https://www.cnblogs.com/clevergirl/p/5699485.html
Copyright © 2011-2022 走看看