AsyncTask

来源:互联网 发布:java读取文件编码格式 编辑:程序博客网 时间:2024/05/16 14:51

AsyncTask的个人使用总结
1. 实现AsyncTask
2. doInBackground:对子线程的封装
3. onProgressUpdate:对子线程进度的更新
4. onPostExecute:对主线程的执行
具体代码:


package com.example.administrator.asynctaskjob;import android.os.AsyncTask;import android.widget.TextView;/****@作者: 乔石*@日期:  2017/6/13*/public class ASyn extends AsyncTask<Object,String,String>{    private TextView textView;//后台运行方法在子线程里面运行//    以及可变参数    @Override    protected String doInBackground(Object... params) {        if (params!=null&&params.length>0){//            第一个位置用来存要请求的地址            String url=params[0]+"";//            第二个位置用来适配要请求到的值            textView =(TextView)params[1];            publishProgress("用来设置更新里面的显示")//            返回要请求的路径通过调用这个方法已经返回我们获取到的字符串了只需要用来适配            String result=UrlUtils.getUrlConnect(url);            return result;        }        return null;    }//主线程用来显示在都InBackground里面的进度    @Override    protected void onProgressUpdate(String... values) {        textView.setText(values[0]);        super.onProgressUpdate(values);    }//也是一个主线程可以拿到do里面的方法来更新主线程的UI    @Override    protected void onPostExecute(String s) {//        其实这个s就相当于中介一样吧子线程里面的resulte取值个了是//        这个方法可以用来适配主线程了、        if (textView !=null){            textView.setText(s);        }        super.onPostExecute(s);    }}

在mainActivity里面的引用

package com.example.administrator.asynctaskjob;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;/****@作者: 乔石*@日期:  2017/6/13*/public class MainActivity extends AppCompatActivity {//直接传入要请求的路径并且得到控件的idprivate final String urlPath = "http://www.tngou.net/api/cook/list?rows=30&id=1";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);//        只要在主方法里面调用        ASyn syn = new ASyn();        syn.execute(urlPath,findViewById(R.id.ttt));    }}

调用网络请求的工具类

package com.example.administrator.asynctaskjob;import android.util.Log;import java.io.InputStream;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URL;import java.util.Map;public class UrlUtils {    public static String postUrlConnect(String urlPath, Map<String,Object> map){        StringBuffer sbRequest =new StringBuffer();        if(map!=null&&map.size()>0){            for (String key:map.keySet()){                sbRequest.append(key+"="+map.get(key)+"&");            }        }        String request = sbRequest.substring(0,sbRequest.length()-1);        try {            //创建URL            URL url = new URL(urlPath);            //由URL的openConnection方法得到一个HttpURLConnection(需要强转)            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();            //设置post提交            httpURLConnection.setRequestMethod("POST");            //设置超时时间            httpURLConnection.setConnectTimeout(30000);            httpURLConnection.setReadTimeout(30000);            httpURLConnection.setDoInput(true);            httpURLConnection.setDoOutput(true);            //把请求正文通过OutputStream发出去            OutputStream os =httpURLConnection.getOutputStream();            os.write(request.getBytes());            os.flush();            //判断响应码  200 代表成功            if(httpURLConnection.getResponseCode()==200){                //由HttpURLConnection拿到输入流                InputStream in=httpURLConnection.getInputStream();                StringBuffer sb=new StringBuffer();                //根据输入流做一些IO操作                byte [] buff =new byte[1024];                int len=-1;                while((len=in.read(buff))!=-1){                    sb.append(new String(buff,0,len,"utf-8"));                }                in.close();                os.close();                httpURLConnection.disconnect();                return  sb.toString();            }else{                return null;            }        }catch (Exception e){            Log.e("post","code:"+e.getMessage());            return null;        }    }    /**     * HttpURLConnection的get请求     * @param urlPath     * @return     */    public static String getUrlConnect(String urlPath){        try {            //创建URL            URL url = new URL(urlPath);            //由URL的openConnection方法得到一个HttpURLConnection(需要强转)            HttpURLConnection httpURLConnection =                    (HttpURLConnection) url.openConnection();            //设置连接            httpURLConnection.connect();            //判断响应码  200 代表成功            if(httpURLConnection.getResponseCode()==200){                //由HttpURLConnection拿到输入流                InputStream in=httpURLConnection.getInputStream();                StringBuffer sb=new StringBuffer();                //根据输入流做一些IO操作                byte [] buff =new byte[1024];                int len=-1;                while((len=in.read(buff))!=-1){                    sb.append(new String(buff,0,len,"utf-8"));                }                in.close();                httpURLConnection.disconnect();                return  sb.toString();            }else{                return null;            }        } catch (Exception e) {            e.printStackTrace();        }        return null;    }}

后面只要在清单文件里面配置一下网络权限并且在布局里面设置布局基本上就完成了。

  • 本人新手,以上只是本人学习的一些观点欢迎指正。
原创粉丝点击