AsyncTask的使用

package com.pingyijinren.test;

import android.os.AsyncTask;
import android.widget.ProgressBar;
import android.widget.TextView;

/**
 * Created by Administrator on 2016/5/18 0018.
 */
class MyAsyncTask extends AsyncTask<Integer,Integer,String>
{
    private TextView txttitle;
    private ProgressBar pgbar;
    public MyAsyncTask(TextView txttitle,ProgressBar pgbar)
    {
        super();

        this.txttitle=txttitle;
        this.pgbar=pgbar;
    }

    //该方法不运行在UI线程中,主要用于异步操作,通过调用publishProgress()方法
    //触发onProgressUpdate对UI进行操作
    @Override
    protected String doInBackground(Integer... params) {
        int i = 0;
        for (i = 10;i <= 100;i+=10)
        {
            try {
                Thread.sleep(1000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            publishProgress(i);
        }
        return  i + params[0].intValue() + "";
    }

    //该方法运行在UI线程中,可对UI控件进行设置
    @Override
    protected void onPreExecute() {
        txttitle.setText("开始执行异步线程~");
    }

    //在doBackground方法中,每次调用publishProgress方法都会触发该方法
    //运行在UI线程中,可对UI控件进行操作
    @Override
    protected void onProgressUpdate(Integer... values) {
        int value = values[0];
        pgbar.setProgress(value);
    }
}
package com.pingyijinren.test;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity{
    private TextView txttitle;
    private ProgressBar pgbar;
    private Button btnupdate;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txttitle=(TextView)findViewById(R.id.txttitle);
        pgbar=(ProgressBar)findViewById(R.id.pgbar);
        btnupdate=(Button)findViewById(R.id.btnupdate);

        btnupdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyAsyncTask myAsyncTask=new MyAsyncTask(txttitle,pgbar);
                myAsyncTask.execute(1000);
            }
        });
    }
}

 

posted @ 2016-05-18 16:06  zqxLonely  阅读(169)  评论(0编辑  收藏  举报