AsyncTask使用总结

来源:互联网 发布:c# 数据库接口开发 编辑:程序博客网 时间:2024/06/06 07:50

官方文档上的:
AsyncTask enables proper and easy use of the UI thread. This class allows you to perform background operations and
publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
我翻译一下哦(害羞):asyncTask可以进行后台操作并将处理好的数据返回到主线程中,而且是在不用handler+thread的情况下.不过了,它只能用在一些耗时相对较少的操作中(不超过几秒),如果你的操作时间较长,对不起,请出门右转到executor+ThreadPoolExecutor and FutureTask那去.

public class AsyncActivity extends Activity {    private TextView info;    private ProgressBar progressBar;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_async);        info = (TextView) findViewById(R.id.textView);        progressBar = (ProgressBar) findViewById(R.id.progressBar);    }    public void asyncClick(View view){        new MyAsyncTask(this).execute();    }    public void downClick(View view){        new DownloadTask(this).execute("http://pic.nipic.com/2008-01-10/200811082741179_2.jpg");    }    /**     * 实现异步;     */    private static class MyAsyncTask extends AsyncTask<String, Integer, String>{        private AsyncActivity activity;        MyAsyncTask(AsyncActivity activity){            this.activity = activity;        }        //执行任务前触发的事件方法,可进行一些初始化的操作,是在UI线程中        @Override        protected void onPreExecute() {            super.onPreExecute();            activity.info.setText("yes!");            //Log.v("start", "start!");        }        //类似于线程,不能访问UI组件        @Override        protected String doInBackground(String... params) {            for(int i = 0; i < 10; i++){                Log.v("start", "wait...");                publishProgress(i);//更新进度                try {                    Thread.sleep(2000);                } catch (InterruptedException e) {                    e.printStackTrace();                }            }            return "success!";        }        //更新进度值        @Override        protected void onProgressUpdate(Integer... values) {            super.onProgressUpdate(values);            activity.info.setText("current:" + values[0]);        }        //是在UI线程中        @Override        protected void onPostExecute(String s) {            super.onPostExecute(s);            activity.info.setText(s);        }    }    //*********************************************************    private static class DownloadTask extends AsyncTask<String, Integer, Integer> {        private AsyncActivity activity;        DownloadTask(AsyncActivity activity) {            this.activity = activity;        }        @Override        protected void onPreExecute() {            super.onPreExecute();            activity.progressBar.setProgress(0);        }        @Override        protected Integer doInBackground(String... params) {            String s = params[0];            try {                URL url = new URL(s);                //open connection                HttpURLConnection conn = (HttpURLConnection) url.openConnection();                int size = conn.getContentLength();//file length;                //0:表示需要更新的最大进度值,1:表示更新当前下载的进度值                publishProgress(0, size);                byte[] bytes = new byte[1000];                int len = -1;                InputStream in = conn.getInputStream();                FileOutputStream out = new FileOutputStream("/sdcard/" + System.currentTimeMillis() + "/.jpg");                while((len = in.read(bytes)) != -1){                    out.write(bytes, 0, len);                    publishProgress(1, len);// Update result;                    out.flush();                }                out.close();            } catch (MalformedURLException e) {                e.printStackTrace();            } catch (IOException e) {                e.printStackTrace();            }            return 200;        }        @Override        protected void onProgressUpdate(Integer... values) {            super.onProgressUpdate(values);            switch (values[0]){                case 0:                    activity.progressBar.setProgress(values[1]);                    break;                case 1:                    activity.progressBar.incrementProgressBy(values[1]);                    break;            }        }        @Override        protected void onPostExecute(Integer integer) {            super.onPostExecute(integer);            if(integer == 200){                activity.info.setText("success!");            }        }    }}
原创粉丝点击