AsyncTask用法总结(Android)

来源:互联网 发布:矩阵分解 翻译 编辑:程序博客网 时间:2024/06/02 08:16

AsyncTask用法总结

完成与2016年10月14日

目录

  • AsyncTask用法总结
    • 目录
    • 简要介绍
    • 优点及缺点
    • 使用方法
    • 使用规则
    • 代码奉上


简要介绍

AsyncTask,是android提供的轻量级的异步类,可以直接继承AsyncTask,在类中实现异步操作,并提供接口反馈当前异步执行的程度(可以通过接口实现UI进度更新),最后反馈执行的结果给UI主线程.

优点及缺点

  • 简单快捷
  • 过程可控
  • 在使用多个异步操作时过于复杂
    (此时使用Handler更好)
  • 无法处理耗时较长的线程的异步处理
    (此时只能用Handler)

使用方法

使用AsyncTask需写一个自定义类去继承他,有2个必须要重写的方法和3个可选是否重写的方法
两个必须重写的方法分别是
doInBackground 用于执行耗时操作
onPostExecute 在doInBackground执行完后调用,此方法为主线程所调用,故可执行UI操作
三个可选重写的方法
onPreExecute 在doInBackground执行前调用,同onPostExecute,此方法也为主线程所调用
onCancelled 在耗时操作被取消时被调用
onProgressUpdate 根据返回的线程执行进度更新UI,同onPostExecute,此方法也为主线程所调用

AsyncTask定义了三个泛型参数,分别用于这5个方法中。
第一个参数为doInBackground的参数类型,在AsyncTask.execute(Param… params);里作为execute方法的参数被传入
第二个参数为onProgressUpdate的参数类型,用于获取执行进度的百分比,一般为Integer
第三个参数为doInBackground的返回类型,onPostExecute和onCancelled的参数类型

最后在Activity中调用自定义类的execute()方法即可

使用规则

  • Task必须在UI Thread中创建
  • execute必须在UI Thread中调用
  • 不要手动的调用这5个重写的方法
  • 该task创建的所有对象都是共用一块内存的,所以该Task只能执行一次,多次执行会有异常
  • 在doInbackground中执行耗时操作即可,不用新开一个线程。因为doInbackground默认已经帮你开启了一个线程

代码奉上

public class UpdateTask extends AsyncTask<String,Integer,Boolean> {    //注意泛型参数类型不能为void,int或boolean,应为Void,Integer,Boolean。因为泛型参数必须为类    //和风天气API的appKey    public static final String MyKey = "xxxxxxxxxxxxxxxxxxxxxxx";    //当前context    final Context context;    //ListView    private ListView listView=null;    //数据库实例    private WeatherDB db;    public UpdateTask(ListView listView,WeatherDB db,Context context){        super();        this.listView = listView;        this.db = db;        this.context = context;    }    //仅用来更新数据的构造方法    public UpdateTask(WeatherDB db, Context context){        super();        this.context = context;        this.db = db;    }    @Override    protected Boolean doInBackground(String... strings) {        boolean is =false;        final String address = "https://api.heweather.com/x3/weather?city=" + strings[0] + "&key=" + MyKey;        //判断是否有网络连接        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);        NetworkInfo[] networkInfos = manager.getAllNetworkInfo();        for (NetworkInfo info : networkInfos) {            if (info.getState() == NetworkInfo.State.CONNECTED) {                is=true;            }        }        if (is) {            HttpURLConnection connection;            try {                URL url = new URL(address);                connection = (HttpURLConnection) url.openConnection();                connection.setRequestMethod("GET");                connection.setConnectTimeout(8000);                connection.setReadTimeout(8000);                InputStream in = connection.getInputStream();                BufferedReader reader = new BufferedReader(new InputStreamReader(in));                StringBuilder response = new StringBuilder();                String line;                while ((line = reader.readLine()) != null) {                    response.append(line);                }                db.saveCity(JsonUtil.getCityFromJson(response.toString()));            } catch (ProtocolException e) {                e.printStackTrace();            } catch (MalformedURLException e) {                e.printStackTrace();            } catch (IOException e) {                e.printStackTrace();            } catch (JSONException e) {                e.printStackTrace();            }        }        return is;    }    @Override    protected void onPostExecute(Boolean b) {        super.onPostExecute(b);        if(b) {            if (listView != null) {                final List<City> cities = db.LoadCity();                CityAdapter adapter = new CityAdapter(context, R.layout.city_item, cities);                listView.setAdapter(adapter);            }        } else {            Toast.makeText(context, "请检查你的网络连接", Toast.LENGTH_SHORT).show();        }    }}
0 0