[Android]异步任务AsyncTask使用解析

public class MyActivity extends Activity{private Button btn;private TextView tv;@Overridepublic void 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(new Button.OnClickListener(){public void onClick(View v) {update();}});}private void update(){UpdateTextTask updateTextTask = new UpdateTextTask(this);updateTextTask.execute();}class UpdateTextTask extends AsyncTask<Void,Integer,Integer>{private Context context;UpdateTextTask(Context context) {this.context = context;}/*** 运行在UI线程中,在调用doInBackground()之前执行*/@Overrideprotected void onPreExecute() {Toast.makeText(context,"开始执行",Toast.LENGTH_SHORT).show();}/*** 后台运行的方法,可以运行非UI线程,可以执行耗时的方法*/@Overrideprotected Integer doInBackground(Void… params) {int i=0;while(i<10){i++;publishProgress(i);try {Thread.sleep(1000);} catch (InterruptedException e) {}}return null;}/*** 运行在ui线程中,在doInBackground()执行完毕后执行*/@Overrideprotected void onPostExecute(Integer integer) {Toast.makeText(context,"执行完毕",Toast.LENGTH_SHORT).show();}/*** 在publishProgress()被调用以后执行,,publishProgress()用于更新进度*/@Overrideprotected void onProgressUpdate(Integer… values) {tv.setText(""+values[0]);}}}

旅游不在乎终点,而是在意途中的人和事还有那些美好的记忆和景色。

[Android]异步任务AsyncTask使用解析

相关文章:

你感兴趣的文章:

标签云: