async task 轻量级异步类,处理简单的异步操作。同时可以更新,此类自己管理和调用thread,stopself如果异步操作比较复杂,用handler
public class MyAsyncTask extends AsyncTask<String,Float,Integer> { TextView textView; ProgressBar progressBar; public MyAsyncTask(TextView txt, ProgressBar bar){ textView = txt; progressBar = bar; } // // params:调用execute时传入的参数,返回值是结果,对应AsyncTask<String,Float,Integer>第三个参数 //publishProgress以后,很快就会调用onProgressUpdate(这个函数有@MainThread,在主线程上调用,可以更新ui) //return 10以后,很快就会调用onPostExecute // @Override protected Integer doInBackground(String... params) { Log.d(MainActivity.TAG,"do in background "+params[0]); for(int i=0;i<10;i++){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } publishProgress((i+1)/10f); } return 10; } @Override protected void onPreExecute() { Log.d(MainActivity.TAG,"on pre execute"); super.onPreExecute(); } @Override protected void onPostExecute(Integer s) { Log.d(MainActivity.TAG,"on post execute "+s); super.onPostExecute(s); } @Override protected void onProgressUpdate(Float... values) { Log.d(MainActivity.TAG,"on progress update" + values[0]); textView.setText(((values[0])*100)+"%"); progressBar.setProgress((int)(values[0]*100)); super.onProgressUpdate(values); }}调用方法:MyAsyncTask asyncTask = new MyAsyncTask(textView,progressBar); asyncTask.execute("走你");
4 async task
最新推荐文章于 2022-02-23 15:04:21 发布