• 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安装nginx
    Linux安装vsftp服务
    maven的Tomcat插件使用
    Mybatis逆向工程生成代码
    千里之行,始于足下
    java 通过反射获取注解
    天气预报需要用到的jar包
    JDBC 利用反射 配置文件
    从网页下载图片的代码
    装箱/拆箱 对象排序
  • 原文地址:https://www.cnblogs.com/zqxLonely/p/5505617.html
Copyright © 2020-2023  润新知