AsyncTask主要用來更新UI線程,比較耗時的操做能夠在AsyncTask中使用。
AsyncTask是一個抽象類,使用時須要繼承這個類,而後調用execute()方法開始執行異步任務。異步
上面的說明涉及到幾個方法:async
publicclassMyActivityextendsActivity
{
privateButton btn;
privateTextView tv;
@Override
publicvoid onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn =(Button) findViewById(R.id.start_btn);
tv =(TextView) findViewById(R.id.content);
btn.setOnClickListener(newButton.OnClickListener(){
publicvoid onClick(View v){
update();
}
});
}
privatevoid update(){
UpdateTextTask updateTextTask =newUpdateTextTask(this);
updateTextTask.execute();
}
classUpdateTextTaskextendsAsyncTask<Void,Integer,Integer>{
privateContext context;
UpdateTextTask(Context context){
this.context = context;
}
/**
* 運行在UI線程中,在調用doInBackground()以前執行
*/
@Override
protectedvoid onPreExecute(){
Toast.makeText(context,"開始執行",Toast.LENGTH_SHORT).show();
}
/**
* 後臺運行的方法,能夠運行非UI線程,能夠執行耗時的方法
*/
@Override
protectedInteger doInBackground(Void... params){
int i=0;
while(i<10){
i++;
publishProgress(i);
try{
Thread.sleep(1000);
}catch(InterruptedException e){
}
}
returnnull;
}
/**
* 運行在ui線程中,在doInBackground()執行完畢後執行
*/
@Override
protectedvoid onPostExecute(Integer integer){
Toast.makeText(context,"執行完畢",Toast.LENGTH_SHORT).show();
}
/**
* 在publishProgress()被調用之後執行,publishProgress()用於更新進度
*/
@Override
protectedvoid onProgressUpdate(Integer... values){
tv.setText(""+values[0]);
}
}
}