您的位置:首页 > 移动开发 > Android开发

android的AsyncTask用法实践

2015-10-07 20:02 633 查看
写了个demo实践异步任务AsyncTask的用法,异步下载网络图片并显示以及模拟进度条、取消异步任务等,大致分以下几部分:

package com.alipay.asynctasktest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

private Button button;
private Button progressBtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
progressBtn = (Button) findViewById(R.id.progressBtn);
button.setOnClickListener(new ButtonClickListener());
progressBtn.setOnClickListener(new ProgressButtionClickListener());
}

class ButtonClickListener implements OnClickListener {

@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, ImageActivity.class));
}

}

class ProgressButtionClickListener implements OnClickListener {

@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, ProgressActivity.class));
}

}
}


/**
* Alipay.com Inc.
* Copyright (c) 2004-2015 All Rights Reserved.
*/
package com.alipay.asynctasktest;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

//AsyncTask注意事项
//必须在UI线程中创建AsyncTask的实例
//必须在UI线程中调用AsyncTask的execute()方法
//重写的四个方法是系统自动调用的,不应手动调用
//每个AsyncTask只能被执行一次,多次调用将会引发异常

/**
*
* @author quyang.ybb
* @version $Id: ImageActivity.java, v 0.1 2015年10月3日 下午4:12:02 quyang.ybb Exp $
*/
public class ImageActivity extends Activity {

private ImageView     mImageView;
private ProgressBar   mProgressBar;
private static String URL = "http://img.my.csdn.net/uploads/201504/12/1428806103_9476.png";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image);
mImageView = (ImageView) findViewById(R.id.image);
mProgressBar = (ProgressBar) findViewById(R.id.pb);
MyAsyncTask task = new MyAsyncTask();
task.execute(URL);
}

/**
* 异步下载图片
* @author quyang.ybb
* @version $Id: MyAsyncTask.java, v 0.1 2015年10月3日 下午12:04:43 quyang.ybb Exp $
*/
public class MyAsyncTask extends AsyncTask<String, Integer, Bitmap> {

// 线程开始前的工作
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.d("aysnctask", "onPreExecute");
mProgressBar.setVisibility(View.VISIBLE);
}

@Override
protected Bitmap doInBackground(String... params) {
Log.d("aysnctask", "doInBackground");
// 获取传递进来的参数
String url = params[0];
Bitmap bitmap = null;
// 定义网络连接对象
URLConnection connection;
// 定义用于获取数据的输入流
InputStream is;
// 导入URL包,通过openConnection()获取网络连接对象
try {
connection = new URL(url).openConnection();
// 获取输入流
is = connection.getInputStream();
//水管------------------流
//水流------------------数据流
//水池-------------------文件
//水桶-------------------程序
BufferedInputStream bis = new BufferedInputStream(is);
//将输入流解析成Bitmap
Thread.sleep(3000);
bitmap = BitmapFactory.decodeStream(bis);
is.close();
bis.close();
} catch (Exception e) {
Log.e("net conn error", "exception");
}
return bitmap;
}

// 当doInBackground方法调用完之后,就会给onPostExecute方法返回一个Bitmap类型的参数
// 操作UI,设置图像
@Override
protected void onPostExecute(Bitmap bitmap) {
Log.d("aysnctask", "onPostExecute");
mProgressBar.setVisibility(View.INVISIBLE);
mImageView.setImageBitmap(bitmap);
}

@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}

}

}


/**
* Alipay.com Inc.
* Copyright (c) 2004-2015 All Rights Reserved.
*/
package com.alipay.asynctasktest;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ProgressBar;

/**
*
* @author quyang.ybb
* @version $Id: ProgressActivity.java, v 0.1 2015年10月7日 下午2:05:10 quyang.ybb Exp $
*/
public class ProgressActivity extends Activity {

private ProgressBar mProgressBar;
private MyAsyncTask mTask;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progressbar);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mTask = new MyAsyncTask();
mTask.execute();
}

@Override
protected void onPause() {
super.onPause();
if (mTask != null && mTask.getStatus() == AsyncTask.Status.RUNNING) {
mTask.cancel(true);
}
}

// 为了能取消异步任务,需要将其与Activity或Fragment的生命周期绑定在一起
public class MyAsyncTask extends AsyncTask<Void, Integer, Void> {

@Override
protected void onPreExecute() {
super.onPreExecute();
Log.d("ProgressActivity", "onPreExecute");
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.d("ProgressActivity", "onPostExecute");
}

//运行在其他线程,其余运行在主流程(可以做更新UI的操作)
@Override
protected Void doInBackground(Void... params) {
// 模拟进度更新
for (int i = 0; i < 100; i++) {
if (isCancelled()) {
break;
}
publishProgress(i);
try {
Thread.sleep(300);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}

@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
mProgressBar.setProgress(values[0]);
}
}
}


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >

<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/loadImage" />

<Button
android:id="@+id/progressBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/loadProgress"/>

</LinearLayout>


<?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="30dp" >

<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent" />

<ProgressBar
android:id="@+id/pb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="gone" />

</RelativeLayout>


<?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:orientation="vertical" >

<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />

</RelativeLayout>


<?xml version="1.0" encoding="utf-8"?>
<resources>

<string name="app_name">com.alipay.asynctasktest</string>
<string name="hello_world">Hello world!</string>
<string name="loadImage">Load Image</string>
<string name="loadProgress">Load ProgressBar</string>
</resources>


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.alipay.asynctasktest"
android:versionCode="1"
android:versionName="1.0" >

<uses-permission android:name="android.permission.INTERNET" />

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ImageActivity" >
</activity>
<activity android:name=".ProgressActivity" >
</activity>
</application>

</manifest>




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: