原型:AsyncTask<Params, Progress, Result>
- Params 表示传入参数类型
- Progress表示处理参数类型
- Result表示返回类型
1 new AsyncTask<String, Void, String>() { 2 3 @Override 4 protected void onCancelled() { 5 // TODO Auto-generated method stub 6 super.onCancelled(); 7 } 8 9 @Override 10 protected void onCancelled(String result) { 11 // TODO Auto-generated method stub 12 super.onCancelled(result); 13 } 14 15 @Override 16 protected void onPostExecute(String result) { 17 super.onPostExecute(result); 18 text.setText(result); 19 } 20 21 @Override 22 protected void onPreExecute() { 23 Toast.makeText(MainActivity.this, "开始读取", Toast.LENGTH_SHORT).show(); 24 super.onPreExecute(); 25 } 26 27 @Override 28 protected void onProgressUpdate(Void... values) { 29 // TODO Auto-generated method stub 30 super.onProgressUpdate(values); 31 } 32 33 @Override 34 protected String doInBackground(String... params) { 35 URL url; 36 try { 37 url = new URL(params[0]); 38 URLConnection conn = url.openConnection(); 39 InputStream is = conn.getInputStream(); 40 InputStreamReader isr = new InputStreamReader(is); 41 BufferedReader br = new BufferedReader(isr); 42 String line; 43 StringBuilder builder = new StringBuilder(); 44 while ((line = br.readLine()) != null) { 45 builder.append(line); 46 } 47 br.close(); 48 is.close(); 49 return builder.toString(); 50 } catch (IOException e) { 51 e.printStackTrace(); 52 } 53 return null; 54 } 55 56 }.execute(url);
- doInBackground(String... params) 参数跟AsyncTask 的第一个参数对应,后台处理放在该方法中;
- onPostExecute(String result) 参数跟AsyncTask 的最后一个参数对应,后台线程执行完后回调,其中result 是 doInBackground的返回结果;
- onPreExecute() 线程执行之前调用;
- onCancelled() 取消时调用;
- onCancelled(String result) 取消时调用;
- onProgressUpdate(Void... values) 处理时回调
时间: 2024-10-13 22:56:35