android_86_AsyncTask
2017-01-20 14:47
183 查看
AsyncTask的作用:
1.子线程中更新UI
2.封装异步任务
效果:
代码:
MainActivity:
自定义的SGAsyncTask
================================================================================================================
下面演示异步下载图片:
效果:
布局:
代码:
================================================================================================================
下面演示异步更新进度条:
效果图:
布局:
代码:
1.子线程中更新UI
2.封装异步任务
效果:
代码:
MainActivity:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 只能调用一次excute SGAsyncTask task = new SGAsyncTask(); task.execute(); }
自定义的SGAsyncTask
package com.sg31.asynctask; import android.os.AsyncTask; public class SGAsyncTask extends AsyncTask { @Override protected void onPreExecute() { super.onPreExecute(); System.out.println("sg__on Pre Execute"); } @Override protected Object doInBackground(Object... params) { System.out.println("sg__do in background"); publishProgress(params); return null; } // 必须在doInBackground方法中,手动调用publishProgress,才会触发本方法onProgressUpdate @Override protected void onProgressUpdate(Object... values) { super.onProgressUpdate(values); System.out.println("sg__on Progress Update"); } @Override protected void onPostExecute(Object result) { super.onPostExecute(result); System.out.println("sg__on Post Execute"); } }
================================================================================================================
下面演示异步下载图片:
效果:
布局:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp" > <ImageView android:id="@+id/imgView" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#1f00" /> <ProgressBar android:id="@+id/progressBar" android:layout_centerInParent="true" android:visibility="invisible" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RelativeLayout>
代码:
package com.sg31.asynctask; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.Visibility; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; public class ImageDownloadActivity extends ActionBarActivity { private ImageView imgView; private ProgressBar progressBar; private static String imgURLString = "http://sg31.com/sgry.png"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_imgdownload); imgView = (ImageView) findViewById(R.id.imgView); progressBar = (ProgressBar) findViewById(R.id.progressBar); new SGImageDownloadAsyncTask().execute(imgURLString); } class SGImageDownloadAsyncTask extends AsyncTask<String, Void, Bitmap>{ @Override protected void onPreExecute() { super.onPreExecute(); // 异步下载前, 让进度条显示 progressBar.setVisibility(View.VISIBLE); } @Override protected void onPostExecute(Bitmap result) { super.onPostExecute(result); // 下载完成后,让进度条隐藏;并设置图片 progressBar.setVisibility(View.INVISIBLE); imgView.setImageBitmap(result); } // 唯一,必须实现的,在后台运行的方法 @Override protected Bitmap doInBackground(String... params) { String imgUrl = params[0]; Bitmap bitmap = null; URLConnection connection = null; InputStream is = null; try { connection = new URL(imgUrl).openConnection(); is = connection.getInputStream(); Thread.sleep(2000); bitmap = BitmapFactory.decodeStream(is); // 千万注意关流 is.close(); } catch (Exception e) { e.printStackTrace(); } return bitmap; } } }
================================================================================================================
下面演示异步更新进度条:
效果图:
布局:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="20dp" > <ProgressBar style="?android:attr/progressBarStyleHorizontal" android:id="@+id/progressBar" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" /> </RelativeLayout>
代码:
package com.sg31.asynctask; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.widget.ProgressBar; public class ProgressBarUpdateActivity extends ActionBarActivity { private ProgressBar progressBar; private ProgressBarUpdateAsyncTask asyncTask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_updateprogressbar); progressBar = (ProgressBar) findViewById(R.id.progressBar); // 使用成员变量,目的是为了能够取消 asyncTask = new ProgressBarUpdateAsyncTask(); // 只能执行一次,否则出错 asyncTask.execute(); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); // 设置停止的标记 if (asyncTask != null && asyncTask.getStatus() == AsyncTask.Status.RUNNING) { asyncTask.cancel(true); } } class ProgressBarUpdateAsyncTask extends AsyncTask<Void, Integer, Void> { @Override protected Void doInBackground(Void... params) { for (int i = 0; i < 100; i++) { // 停止,其实是通过标记,手动退出循环 if (isCancelled()) { break; } // 必须通过此方法,激活onProgressUpdate方法;传递过去的参数就是当前进度 publishProgress(i); try { Thread.sleep(50); } catch (Exception e) { e.printStackTrace(); } } return null; } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); // 这儿可更新UI progressBar.setProgress(values[0]); } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); finish(); } } }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件