AsyncTask
来源:互联网 发布:php编程代码大全 编辑:程序博客网 时间:2024/06/05 10:12
第一步:在布局文件中添加相应的控件。
<Button
android:id="@+id/download"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下载"/>
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="当前的进度为"/>
<ProgressBar
android:id="@+id/pb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"/>
第二步:声明属性并进行初始化。
Button download;
ProgressBar pb;
TextView tv;
download = (Button) findViewById(R.id.download);
pb = (ProgressBar) findViewById(R.id.pb);
tv = (TextView) findViewById(R.id.tv);
第三步:创建一个内部类,继承自AsyncTask
//AsyncTask使用第1步:创建一个内部类,继承AsyncTaskclass DownLoadTask extends AsyncTask<Integer,Integer,String> { //上面三个参数是不固定的,可以更改,这里是因为这个Demo的关系, //一个代表休眠时间,还有一个是返回值类型 //任务开始的时候会自动执行这个方法 @Override protected void onPreExecute() { super.onPreExecute(); } //后台执行的方法 @Override protected String doInBackground(Integer... integers) { //模拟下载的进度,进行进度的更新 for (int i=0; i<101 ;i++){ //调用方法进行界面更新 publishProgress(i); //线程休眠一秒,模拟数据的获取 try{ Thread.sleep(integers[0]); }catch (InterruptedException e){ e.printStackTrace(); } } return"执行完毕"; } //当界面更新的时候自动调用 @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); //这个方法是在别的方法中调用的publishprogress 时自动被调用的 // 他的参数是一个不定长的参数,即参数的个数不一定,相当于一个数组, //第n个数就是values【i】 tv.setText(values[0] +"%"); //还要进行界面上的progressbar 的更新 pb.setProgress(values[0]); } //当执行完成的时候进行调用的方法 @Override protected void onPostExecute(String s) { super.onPostExecute(s); }}//给download 的按钮添加响应事件download.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { DownLoadTask task = new DownLoadTask(); task.execute(100); }
- AsyncTask
- ASyncTask
- AsyncTask
- AsyncTask
- AsyncTask
- AsyncTask
- AsyncTask
- AsyncTask
- AsyncTask
- AsyncTask
- AsyncTask
- AsyncTask
- AsyncTask
- AsyncTask
- AsyncTask
- AsyncTask
- AsyncTask
- AsyncTask
- hdu 1015 Safecracker
- 工欲善其事,必先利其器,webstorm走起
- Servlet中Cookie
- SGU_390_Tickets(另类数位DP)
- 文件读取
- AsyncTask
- 2.Hibernate三个准备
- listview分组
- Mac 配置mysql 别名 alias
- Java基础四
- 格式符函数printf()、sprintf()、 vprintf()、 vsprintf()、 fprintf() 和 vfprintf()
- vs vc 编译选项
- 几个javascript技巧
- 支持移动端,PC端图片弹出层(支持键盘)