AsyncTask异步交互的用法简介

来源:互联网 发布:淘宝售假扣48分重开店 编辑:程序博客网 时间:2024/06/05 03:53

首先定义一个类,继承AsyncTask类,并实现相关方法:

<span style="font-size:18px;">/** * @author WJL <span style="color:#ff0000;">第一个泛型:规定doInBackground方法的参数类型,规定AsyncTask.execute方法传递的参数类型 *         第二个泛型:规定onProgressUpdate方法参数的类型,publishProgress参数类型 *         第三个泛型:规定doInBackground方法的返回值类型</span> */public class MyAsyncTask extends AsyncTask<String, Double, String> {TextView textView; ProgressBar bar;/** * @param textView * @param bar  */public MyAsyncTask(TextView textView, ProgressBar bar) {this.textView=textView;this.bar=bar;}// Runs on the UI thread before doInBackground.@Override// 运行在主线程,在doInBackground方法之前执行protected void onPreExecute() {System.out.println("准备联网");}@Override// 运行在子线程,做耗时操作// 返回值被onPostExecute接收<span style="color:#ff0000;">protected String doInBackground(String... params)</span> {String string = "100";HttpClient httpClient = new DefaultHttpClient();// 做联网请求,得到传递的参数,因为是可变长度的数组,想取第一个参数,所以去角标为0的元素HttpGet httpGet = new HttpGet(params[0]);try {HttpResponse httpResponse = httpClient.execute(httpGet);if (httpResponse.getStatusLine().getStatusCode() == 200) {HttpEntity httpEntity = httpResponse.getEntity();//得到实体里的json string = EntityUtils.toString(httpEntity);}} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} return string;}// Runs on the UI thread after doInBackground.// 运行在主线程,在doInBackground方法之后执行,接收doInBackground方法的返回值</span>
<span style="font-size:18px;">在此方法内更新UI线程中的控件<span style="color:#ff0000;">protected void onPostExecute(String result)</span> { System.out.println(result); //更新进度// publishProgress(100d);};// 更新进度,运行在主线程上,在publishProgress运行之后protected void onProgressUpdate(Double[] values) {//System.out.println("执行进度:" + values[0]);double r = values[0];//向上取整double floor = Math.ceil(r );textView.setText(floor+"");//bar.setProgress(double.);};//获取进度public void progress(){/*// 获取数据总长度long contentLength = httpEntity.getContentLength();System.out.println(contentLength);// 获取网络数据InputStream inputStream = httpEntity.getContent();BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));char[] buf = new char[1];        //总读取进度int sun = 0;//本次读取的进度        int i;        StringBuilder buffer=new StringBuilder();while ((i = bufferedReader.read(buf)) != -1) {sun=sun+i;double count = (((double)sun / (double)contentLength))*100;             //实时更新进度publishProgress(count); buffer.append(new String(buf));}bufferedReader.close();inputStream.close();       string = buffer.toString();*/////////////////////////////////////////////////}}</span>

在UI主线程调用(注:创建一个MyAsyncTask对象,只能调用一次excute方法)

<span style="font-size:18px;">public class MainActivity extends Activity {//String path="http://169.254.214.171:8080/bwie/city.json";String key = "3ac9f31ff66b9746539472887b3799c3";// 通过get请求时的接口地址String get_path = "http://web.juhe.cn:8080/constellation/getAll?consName=狮子座&type=today&key="+ key;private TextView textView;private ProgressBar bar;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);textView = (TextView) findViewById(R.id.textView);ProgressBarbar = (ProgressBar) findViewById(R.id.pro);MyAsyncTask myAsyncTask=new MyAsyncTask(textView,bar);try {String string = myAsyncTask.execute(get_path).get();textView.setText(string);System.out.println(string);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}</span>


0 0
原创粉丝点击