編輯:關於Android編程
布局文件main.xml
核心代碼:main.java
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 {
@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);
}
}
}
7.效果圖,有失真,想看高清,自己試下代碼,github鏈接地址
8.補充原則:
AsyncTask類必須在UI Thread當中加載,在Android中這些都是自動完成的 AsyncTask的對象必須在UI Thread當中實例化 execute方法必須在UI Thread當中調用 不要手動的去調用AsyncTask的四個方法,這些都是由Android系統自動調用的 AsyncTask任務只能被執行一次
9.如果取消Task,可以通過調用cancle方法,這個較簡單就不介紹了。
10.AsyncTask源碼分析:
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);
}
}
};
}
..................
}
一:Log日志工具類 一個android應用程序運行後 並不會在 ide的控制台內輸出任何信息. 不能在控制台輸出。但是android提供的Log類。 在程序中輸出日志
Volley 是一個 HTTP 庫,它能夠幫助 Android app 更方便地執行網絡操作,最重要的是,它更快速高效。我們可以通過開源的 AOSP 倉庫獲取到 Voll
本文實例為大家分享了android遍歷所有文件夾和子目錄來搜索文件,供大家參考,具體內容如下java代碼:import java.io.File;import andro
Cocos2d-x移植到Android平台編譯的兩個文件Android.mk和Application.mk2014年6月11日 本篇博客主要講NDK編譯Android項目