android线程通信之Asynctask

来源:互联网 发布:苹果最新系统下载软件 编辑:程序博客网 时间:2024/05/22 14:05

这篇文章我们来谈谈android线程通信中的Asynctask,首先这是一个抽象的类,如果我们要使用它,我们必须有一个它的实现子类,并重写它的四个方法,在我的代码之中,我对每个方法都有详细的介绍,因为一个Asynctask只能execute一次,所以我的这个计数程序有点小问题,你们可以通过暂停等按钮的不可点击,然后再启动按钮以后再恢复按钮的点击,当然启动按钮会重新给一个新的对象,我把代码贴出来大家参考。当然,和以往一样,布局代码就不贴了,只贴java代码

package com.jk.asynctaskdemo;import android.os.AsyncTask;import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity implements OnClickListener {//declare variable objectTextView tv;MyTask myTask;Button btn_start, btn_begin, btn_pause, btn_stop;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);init();}public void init() {//bundle the widget with the idtv = (TextView) findViewById(R.id.tv_count);btn_start = (Button) findViewById(R.id.btn_start);btn_begin = (Button) findViewById(R.id.btn_begin);btn_pause = (Button) findViewById(R.id.btn_pause);btn_stop = (Button) findViewById(R.id.btn_stop);//set the onclick eventbtn_start.setOnClickListener(this);btn_begin.setOnClickListener(this);btn_pause.setOnClickListener(this);btn_stop.setOnClickListener(this);//instantiation myTaskmyTask = new MyTask();}@Overridepublic void onClick(View v) {//judge different click eventswitch (v.getId()) {case R.id.btn_start:myTask.isrun = true;myTask.execute(0);break;case R.id.btn_begin:myTask.ispause = false;break;case R.id.btn_pause:myTask.ispause = true;break;case R.id.btn_stop:myTask.isrun = false;}}//first params,the type of the parameter that you need to send when you launch the task//second progress,the type of the parameter that be send when the onProgressUpdata method is running//third result,the type of doInBackground method return,and the onPostExecute receiveclass MyTask extends AsyncTask<Integer, Integer, Integer> {int i = 0;boolean isrun;boolean ispause;        //the method is running in the subthread,always run the longtime task@Overrideprotected Integer doInBackground(Integer... params) {while (isrun) {while(ispause){}//call the onProgressUpdata methodpublishProgress(++i);try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return null;}         //running in main thread ,and running after doInBackground@Overrideprotected void onPostExecute(Integer result) {// TODO Auto-generated method stubsuper.onPostExecute(result);}        //running in main thread,and running before doInBackground@Overrideprotected void onPreExecute() {// TODO Auto-generated method stubsuper.onPreExecute();}         //running in main thread,and called by publishProgress@Overrideprotected void onProgressUpdate(Integer... values) {tv.setText(""+values[0]);super.onProgressUpdate(values);}}}




0 0
原创粉丝点击