IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]AsyncTask使用入门

    lincyang发表于 2011-07-19 17:41:15
    love 0
    最近要使用AsyncTask做一些后台工作,今天先发一个入门的程序,待linc使用熟练后再发个心得。呵呵。当然,做后台工作可以使用Thread直接来搞。见之前的一篇文章《Android中线程和进度条的使用》,http://blog.csdn.net/lincyang/article/details/5861221


    好吧,这个例子最简单了,直接上代码:

    xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
    <TextView    
        android:id="@+id/Text"  
        android:layout_width="fill_parent"   
        android:layout_height="wrap_content"   
        android:textSize="30sp"  
        android:textColor="#FF0000"  
        android:text="@string/hello"  
        /> 
    <Button
    	android:id="@+id/BtnCancel"
        android:layout_width="fill_parent"   
        android:layout_height="wrap_content" 
        android:text="Cancel"	
    />    
    </LinearLayout>
    



    java

    package com.linc.TestAsyncTask;
    
    import android.app.Activity;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.os.SystemClock;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class TestAsyncTask extends Activity {
    	 private TextView textView;  
    	 private Button btnCancel;
    	 
    	 private mAsyncTask mTask;  
    	 
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            
            textView=(TextView)findViewById(R.id.Text);  
            textView.setText("准备"); 
            
            btnCancel=(Button)findViewById(R.id.BtnCancel);
            btnCancel.setOnClickListener(new View.OnClickListener() {
    			
    			@Override
    			public void onClick(View v) {
    				// TODO Auto-generated method stub
    				mTask.cancel(true);
    			}
    		});
            
            mTask=new mAsyncTask();
            mTask.execute("开始");
        }
        
        
        //其中  
        //参数1:向后台任务的执行方法传递参数的类型;  
        //参数2:在后台任务执行过程中,要求主UI线程处理中间状态,通常是一些UI处理中传递的参数类型;  
        //参数3:后台任务执行完返回时的参数类型 。   
        private class mAsyncTask extends AsyncTask<String/*参数1*/,String/*参数2*/,String/*参数3*/>  
        {  
            @Override  
            protected String/*参数3*/ doInBackground(String... params/*参数1*/) {  
                String pre = params[0];  
                for (int i = 0; i < 5; i++) {  
                    publishProgress(pre+i/*参数2*/);  
                    SystemClock.sleep(1000);  
                }  
                return "结束";  
            }  
            @Override  
            protected void onPostExecute(String result/*参数3*/) {  
                super.onPostExecute(result);  
                Toast.makeText(TestAsyncTask.this, result, Toast.LENGTH_SHORT).show();//提示任务结束  
                textView.setText(result);  
            }  
              
            protected void onPreExecute() {  
                Toast.makeText(TestAsyncTask.this, "开始执行任务" + this,  
                        Toast.LENGTH_SHORT).show();  
            }  
      
            //  
            protected void onProgressUpdate(String... values/*参数2*/ ) {  
    //          textView.append(values[0]);  
                textView.setText(values[0]);  
            }  
              
            //onCancelled方法用于在取消执行中的任务时更改UI  
            @Override  
            protected void onCancelled() {  
                textView.setText("cancelled");  
            }  
        }  
    }


    使用时要注意api文档中线程规则第四条:The task can be executed only once (an exception will be thrown if a second execution is attempted.)

    也就是说,一个asyncTask只能使用一次,当你想再次使用的话,只好再new一个任务,否则要报异常的。

    ERROR/AndroidRuntime(1936): FATAL EXCEPTION: main
    ERROR/AndroidRuntime(1936): java.lang.IllegalStateException: Cannot execute task: the task has already been executed (a task can be executed only once)
    


     


     





沪ICP备19023445号-2号
友情链接