标签:
AsyncTask主要用来更新UI线程,比较耗时的操作可以在AsyncTask中使用。
AsyncTask是一个抽象类,使用时需要继承这个类,然后调用execute()方法开始执行异步任务。
上面的说明涉及到几个方法:
publicclassMyActivityextendsActivity{privateButton btn;privateTextView tv;@Overridepublicvoid 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()之前执行 */@Overrideprotectedvoid onPreExecute(){Toast.makeText(context,"开始执行",Toast.LENGTH_SHORT).show();}/** * 后台运行的方法,可以运行非UI线程,可以执行耗时的方法 */@OverrideprotectedInteger doInBackground(Void... params){int i=0;while(i<10){ i++; publishProgress(i);try{Thread.sleep(1000);}catch(InterruptedException e){}}returnnull;}/** * 运行在ui线程中,在doInBackground()执行完毕后执行 */@Overrideprotectedvoid onPostExecute(Integer integer){Toast.makeText(context,"执行完毕",Toast.LENGTH_SHORT).show();}/** * 在publishProgress()被调用以后执行,publishProgress()用于更新进度 */@Overrideprotectedvoid onProgressUpdate(Integer... values){ tv.setText(""+values[0]);}}}标签:
原文地址:http://www.cnblogs.com/o87481299/p/4199904.html