<uses-permission android:name="android.permission.INTERNET">uses-permission>
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.dragon.asynctask.Main">
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="13dp"
android:text="下载"/>
RelativeLayout>
package com.dragon.asynctask;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Main extends AppCompatActivity {
private final String TAG="asynctask";
private ImageView mImageView;
private Button mButton;
private ProgressDialog mDialog;
// the path of image
private String mImagePath="http://g.hiphotos.baidu.com/image/h%3D360/sign=4df699dff536afc3110c39638318eb85/908fa0ec08fa513d682eb8c13f6d55fbb2fbd92d.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// add Dialog
mDialog = new ProgressDialog(this);
// this dialog will never occur,if your network is good.
mDialog.setTitle("attention");
mDialog.setMessage("waiting ... ...");
mImageView = (ImageView)findViewById(R.id.image);
// mImageView.setScaleType(ImageView.ScaleType.FIT_XY);//when picture doesn't fit your phone,if can use this.
mButton = (Button) findViewById(R.id.button);
// listener
mButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
// new async task
DownTask task = new DownTask();
// must be execute int the UI thread also called Main thread.
task.execute(mImagePath);
}
});
}
// AsyncTask provided by google.
public class DownTask extends AsyncTask<String,Void,Bitmap> {
@Override
protected void onPreExecute(){
mDialog.show();
}
// the params is variable
protected Bitmap doInBackground(String ... params){
URL imageUrl = null;
Bitmap mBitmap=null;
InputStream inputData=null;
HttpURLConnection urlConn=null;
try{
imageUrl = new URL(params[0]);
}catch (MalformedURLException e){
e.printStackTrace();
}
// get the net data using httpclient.
try {
urlConn =(HttpURLConnection) imageUrl.openConnection();
urlConn.setDoInput(true);
urlConn.connect();
// convert to inputStream
inputData = urlConn.getInputStream();
// decode
mBitmap = BitmapFactory.decodeStream(inputData);
inputData.close();
}catch(IOException e){
Log.e(TAG,e.getMessage());
}finally{
try {
if(inputData != null){
inputData.close();
}
if( urlConn != null){
urlConn.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return mBitmap;
}
// when doinbackground is over, next thing we should do.
@Override
protected void onPostExecute(Bitmap result){
super.onPostExecute(result);
// show picture in the UI view.
mImageView.setImageBitmap(result);
// disable this dialog.
mDialog.dismiss();
// let the button invisible, so we can see more comfortable, you konw.
mButton.setVisibility(View.INVISIBLE);
}
}
}
public abstract class AsyncTask {
//获得当前运行状态的cup数
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
//根据当前机器CUP的个数决定线程池中的线程个数
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
//获得线程池中最大线程数
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
//线程的存活时间
private static final int KEEP_ALIVE = 1;
//线程工厂,为线程池创建所需线程
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
//线程池中的缓存队列,此处为128个
private static final BlockingQueue sPoolWorkQueue =
new LinkedBlockingQueue(128);
/**
* An {@link Executor} that can be used to execute tasks in parallel.
*/
//根据以上参数,构造线程池执行器
public static final Executor THREAD_POOL_EXECUTOR
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
/**
* An {@link Executor} that executes tasks one at a time in serial
* order. This serialization is global to a particular process.
*/
//获得顺序执行的线程池执行器
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
//异步任务处理结果码和进度更新码
private static final int MESSAGE_POST_RESULT = 0x1;
private static final int MESSAGE_POST_PROGRESS = 0x2;
//内部类,消息的执行者handler对象
private static final InternalHandler sHandler = new InternalHandler();
//线程池中默认的执行器
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
//异步任务回调接口
private final WorkerRunnable mWorker;
private final FutureTask mFuture;
//当前异步任务的状态,初始状态为“未执行”状态
private volatile Status mStatus = Status.PENDING;
private final AtomicBoolean mCancelled = new AtomicBoolean();
private final AtomicBoolean mTaskInvoked = new AtomicBoolean();
......................
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*/
//创建一个新的异步任务,该构造方法必须在UI线程中调用
public AsyncTask() {
mWorker = new WorkerRunnable() {
public Result call() throws Exception {
mTaskInvoked.set(true); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
return postResult(doInBackground(mParams));
}
};
mFuture = new FutureTask(mWorker) {
@Override
protected void done() {
try {
postResultIfNotInvoked(get());
} catch (InterruptedException e) {
android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occured while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}
..................
}
1.http://blog.csdn.net/dmk877/article/details/49366421
2.http://blog.csdn.net/feiduclear_up/article/details/46860015
3.http://www.cnblogs.com/smyhvae/p/3866570.html
4.http://www.cnblogs.com/mythou/p/3191174.html
5.http://www.cnblogs.com/_ymw/p/4140418.html
6.http://blog.csdn.net/wdaming1986/article/details/40828453