异步任务之AsyncTASK

主线程1执行//onPreExecute在主线程中执行命令  可有可无 通常做进度条的初始化

@Override

protected void onPreExecute() {

    super.onPreExecute();

}

子线程2执行//doInBackground在子线程中执行命令

@Override

protected String doInBackground(String... params) {

    HttpURLConnection con=null;

    InputStream is=null;

    StringBuilder sbd=new StringBuilder();

    try {

        URL url=new URL(params[0]);

        con= (HttpURLConnection) url.openConnection();

        con.setConnectTimeout(5000);

        con.setReadTimeout(5*1000);

       

        if (con.getResponseCode()==200){

            is=con.getInputStream();

            int next=0;

            byte[] bt=new byte[1024];

            while ((next=is.read(bt))>0){

                sbd.append(new String(bt,0,next));

            }

        }

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }finally {

        if (is!=null){

            try {

                is.close();

            } catch (IOException e) {

                e.printStackTrace(); }}

        if (con!=null){

            con.disconnect();} } 

return sbd.toString();}

调用publishProgress(progress。。。)被onProgress

主线程3//onPostExecute在UI线程中执行

@Override

protected void onPostExecute(String s) {

    super.onPostExecute(s);

    show.setText(s);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值