zoukankan      html  css  js  c++  java
  • 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);
                }
            });
        }
    }
  • 相关阅读:
    鸟哥的 Linux 私房菜Shell Scripts篇(一)
    证券投资基金会计核算业务指引
    在LINUX上部署SOFA
    bash: sz: command not found
    git常用命令
    git删除指定commit
    dubbo-本地直连
    java 中的锁 -- 偏向锁、轻量级锁、自旋锁、重量级锁
    设置Chrome忽略网站证书错误
    mybatis-传多个参数
  • 原文地址:https://www.cnblogs.com/zqxLonely/p/5505617.html
Copyright © 2011-2022 走看看