AsyncTask基本结构介绍

参数介绍

Params   运行参数
Progress 后台任务执行中返回的进度值的类型
Result      后台执行任务完成后返回结果的类型			返回的参数类型

AsyncTask回调的方法

dolnBackground   必须重写,异步执行后台线程操作将要完成的任务
onPreExecute 执行后台耗时操作前被调用,通常用户完成一些初始化操作
onPostExecute    当dolnBackground ()完成后系统自动调用 onPostExecute ()方法 ,并将dolnBackground 返回值传给该方法
onProgressUpdata  在dolnBackground 方法中调用publishProgress方法更新任务的·执行进度后就会触发该方法;
实例代码
/**
 * 实现网络的异步访问
 */
public class NewsAsyncTask extends AsyncTask> {
    private ListView lsvMain;		//从activity  传过来的listView对象

    private Context context;
    private JSONObject jsonObject;
    private NewsBean newsBean;		//实体类
    @Override
    protected List doInBackground(String... strings) {
        return getJsonData(strings[0]);
    }

    @Override
    protected void onPostExecute(List list) {
        super.onPostExecute(list);
        NewsAdapter adapter = new NewsAdapter(list,context,lsvMain);
        lsvMain.setAdapter(adapter);
    }

    public void setAdapter(ListView lsvMain,Context context){
        this.lsvMain = lsvMain;
        this.context = context;
    }
    /**
     * 将url对应的JSON格式数据转化为我们所封装的NewsBean
     * @param url
     * @return
     */
    private List getJsonData(String url){
        List list = new ArrayList<>();
        try {
            /**
             * new URL(url).openStream() 根据URL直接获取互联网数据,返回类型IInputStream
             */
            String jsonString = readStream(new URL(url).openStream());
            jsonObject = new JSONObject(jsonString);
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            for(int i = 0;i < jsonArray.length();i++){
                jsonObject = jsonArray.getJSONObject(i);
                newsBean = new NewsBean();
                newsBean.setIconUri(jsonObject.getString("picSmall"));
                newsBean.setTitle(jsonObject.getString("name"));
                newsBean.setContent(jsonObject.getString("description"));
                list.add(newsBean);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 通过InputStream解析网页返回的数据
     * @param is
     * @return
     */
    private String readStream(InputStream is){
        InputStreamReader isr;
        String result = "";
        try {
            String line = "";
            isr = new InputStreamReader(is,"utf-8");        //通过InputStreamReader将字节流转化为字符流
            BufferedReader bufferedReader = new BufferedReader(isr);
            StringBuilder builder = new StringBuilder();
            while((line = bufferedReader.readLine()) != null){
                builder.append(line);
            }
            result = builder.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}

你可能感兴趣的:(android,AsyncTask)