1. 程式人生 > >Android AsyncTask 非同步操作Demo

Android AsyncTask 非同步操作Demo

AysncTask是安卓提供的輕便非同步操作類,在類中直接實現非同步操作,並使用提供的介面,反饋當前非同步操作的執行進度,也就是說可以通過介面實現UI程序的非同步更新,或者說將執行的結果返回給UI主執行緒。這裡通過獲取blog.csdn.net的程式碼為例。


public class MainActivity extends Activity {

private TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = (TextView)findViewById(R.id.tttt);
    findViewById(R.id.btn).setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View arg0){

            ReadURL("http://blog.csdn.net");
        }



    });

}
public void ReadURL(String url){
    new AsyncTask<String, Void , String>(){



        @Override
        protected String doInBackground(String... arg0){

            try{
                URL url = new URL(arg0[0]);
                URLConnection connection = url.openConnection();
                InputStream iStream = connection.getInputStream();
                InputStreamReader isr = new InputStreamReader(iStream);
                BufferedReader br = new BufferedReader(isr);
                String line;
                StringBuilder builder = new StringBuilder();
                while((line = br.readLine())!=  null){
                    builder.append(line);
                }
                br.close();
                iStream.close();
                return builder.toString();
            } catch (MalformedURLException e){

                e.printStackTrace();
            }catch (IOException e){
                e.printStackTrace();
            }


            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String s) {
            textView.setText(s);
            super.onPostExecute(s);
            System.out.println(s);
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onCancelled(String s) {
            super.onCancelled(s);
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }
    }.execute(url);

}

}
“`
注意幾個易錯點.
line = br.readLine()! = null 不可寫為” “