AsyncTask初探

activity_main.xml

<RelativeLayout 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"
    tools:context="com.example.asynctask.MainActivity" >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp" />

    <ProgressBar
        android:id="@+id/progressBar"
        android:visibility="gone"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

</RelativeLayout>

MainActivity

package com.example.asynctask;

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

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

public class MainActivity extends Activity {

	private ImageView imageView;
	private ProgressBar progressBar;
private static String url = "http://img.mukewang.com/55237dcc0001128c06000338-300-170.jpg";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		imageView = (ImageView) findViewById(R.id.imageView);
		progressBar = (ProgressBar) findViewById(R.id.progressBar);

		new MyAsycTask().execute(url);
	}

	/**
	 * 第一个参数是运行参数 第二个参数是progress是加载的进度 第三个参数是返回的类型是bitmap
	 * 
	 */
	class MyAsycTask 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.GONE);
			imageView.setImageBitmap(result);
		}

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

		@Override
		protected Bitmap doInBackground(String... params) {
			// 因为只传一个参数
			Bitmap bitmap = null;
			String url = params[0];
			URLConnection connection;
			InputStream inputStream;
			try {
				// 打开连接
				connection = new URL(url).openConnection();
				// 获取输入流,读取网络数据
				inputStream = connection.getInputStream();
				// 包装下
				BufferedInputStream bis = new BufferedInputStream(inputStream);
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				// 直接返回一个图片
				bitmap = BitmapFactory.decodeStream(bis);
				// 关闭流
				inputStream.close();
				bis.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return bitmap;
		}

	}
}

**********************************************异步任务的取消操作*************************************

activity_main.xml

<RelativeLayout 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"
    tools:context="com.example.asynctask.MainActivity" >

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

</RelativeLayout>

MainActivity
package com.example.asynctask;

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

public class MainActivity extends Activity {
	private ProgressBar progressBar;
	private MyAsyncTask task;

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

	/**
	 * back键返回时候,将异步任务标记为取消状态--实际没有取消
	 */
	 @Override
	 protected void onPause() {
	 super.onPause();
	 if (task != null && task.getStatus() == AsyncTask.Status.RUNNING) {
	 task.cancel(true);
	 }
	
	 }

	class MyAsyncTask extends AsyncTask<Void, Integer, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			for (int i = 0; i < 100; i++) {
				// 如果返回,从新进入后,判断取消状态,如果为true,就不会发布进度,终止循环
				 if (isCancelled()) {
				 break;
				 }
				publishProgress(i);
				try {
					Thread.sleep(300);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			return null;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			// 这里也需要判断下,直接返回即可
			 if (isCancelled()) {
			 return;
			
			 }
			if (progressBar!=null) {
				
				progressBar.setProgress(values[0]);
				
			}
		}

	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值