Android中AsyncTask的用法实例分享

2019-12-10 20:09:30刘景俊

    * onPostExecute(Result) 此方法在主线程执行,任务执行的结果作为此方法的参数返回。

      PageTask扩展了AsyncTask,在 doInBackground()方法中读取网页内容。PageTask的源代码如下所示:

 

复制代码
// 设置三种类型参数分别为String,Integer,String  
    class PageTask extends AsyncTask<String, Integer, String> {  

        // 可变长的输入参数,与AsyncTask.exucute()对应  
        @Override  
        protected String doInBackground(String... params) {  
            try {  
                HttpClient client = new DefaultHttpClient();  
                // params[0] 代表连接的url  
                HttpGet get = new HttpGet(params[0]);  
                HttpResponse response = client.execute(get);  
                HttpEntity entity = response.getEntity();  
                long length = entity.getContentLength();  
                InputStream is = entity.getContent();  
                String s = null;  
                if (is != null) {  
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
                    byte[] buf = new byte[128];  
                    int ch = -1;  
                    int count = 0;  
                    while ((ch = is.read(buf)) != -1) {