AsyncTask主要用来更新UI线程,比较耗时的操作可以在AsyncTask中使用。
AsyncTask是个抽象类,使用时需要继承这个类,然后调用execute()方法。注意继承时需要设定三个泛型Params,Progress和Result的类型,如AsyncTask<Void,Inetger,Void>:
- Params是指调用execute()方法时传入的参数类型和doInBackgound()的参数类型
- Progress是指更新进度时传递的参数类型,即publishProgress()和onProgressUpdate()的参数类型
- Result是指doInBackground()的返回值类型
上面的说明涉及到几个方法:
- doInBackgound() 这个方法是继承AsyncTask必须要实现的,运行于后台,耗时的操作可以在这里做
- publishProgress() 更新进度,给onProgressUpdate()传递进度参数
- onProgressUpdate() 在publishProgress()调用完被调用,更新进度
好了,看下实际的例子,了解一下怎么使用吧:
- publicclassMyActivityextendsActivity
- {
- privateButtonbtn;
- privateTextViewtv;
- @Override
- publicvoidonCreate(BundlesavedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- btn=(Button)findViewById(R.id.start_btn);
- tv=(TextView)findViewById(R.id.content);
- btn.setOnClickListener(newButton.OnClickListener(){
- publicvoidonClick(Viewv){
- update();
- }
- });
- }
- privatevoidupdate(){
- UpdateTextTaskupdateTextTask=newUpdateTextTask(this);
- updateTextTask.execute();
- }
- classUpdateTextTaskextendsAsyncTask<Void,Integer,Integer>{
- privateContextcontext;
- UpdateTextTask(Contextcontext){
- this.context=context;
- }
- /**
- *运行在UI线程中,在调用doInBackground()之前执行
- */
- @Override
- protectedvoidonPreExecute(){
- Toast.makeText(context,"开始执行",Toast.LENGTH_SHORT).show();
- }
- /**
- *后台运行的方法,可以运行非UI线程,可以执行耗时的方法
- */
- @Override
- protectedIntegerdoInBackground(Void...params){
- inti=0;
- while(i<10){
- i++;
- publishProgress(i);
- try{
- Thread.sleep(1000);
- }catch(InterruptedExceptione){
- }
- }
- returnnull;
- }
- /**
- *运行在ui线程中,在doInBackground()执行完毕后执行
- */
- @Override
- protectedvoidonPostExecute(Integerinteger){
- Toast.makeText(context,"执行完毕",Toast.LENGTH_SHORT).show();
- }
- /**
- *在publishProgress()被调用以后执行,publishProgress()用于更新进度
- */
- @Override
- protectedvoidonProgressUpdate(Integer...values){
- tv.setText(""+values[0]);
- }
- }
- }