XUtils3--程式碼詳解(一)
官方readme.me
- xUtils 包含了很多實用的android工具.
- xUtils 支援超大檔案(超過2G)上傳,更全面的http請求協議支援(11種謂詞),擁有更加靈活的ORM,更多的事件註解支援且不受混淆影響…
- xUtils 最低相容Android 4.0 (api level 14). (Android 2.3?)
- xUtils3變化較多所以建立了新的專案不在舊版(github.com/wyouflf/xUtils)上繼續維護, 相對於舊版本:
– HTTP實現替換HttpClient為UrlConnection, 自動解析回撥泛型, 更安全的斷點續傳策略.
– 支援標準的Cookie策略, 區分domain, path…
– 事件註解去除不常用的功能, 提高效能.
– 資料庫api簡化提高效能, 達到和greenDao一致的效能.
– 圖片繫結支援gif, webp; 支援圓角, 圓形, 方形等裁剪, 支援自動旋轉…
需要許可權:
<uses-permissionandroid:name="android.permission.INTERNET" />
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE" />
初始化:
// 在application的onCreate中初始化
@Overridepublicvoid onCreate() {
super.onCreate();
x.Ext.init(this);
x.Ext.setDebug(true); // 是否輸出debug日誌...
}
訪問網路
/** * 自定義實體引數類請參考: * 請求註解 {@link org.xutils.http.annotation.HttpRequest} * 請求註解處理模板介面 {@link org.xutils.http.app.ParamsBuilder} * * 需要自定義型別作為callback的泛型時, 參考: * 響應註解 {@link org.xutils.http.annotation.HttpResponse} * 響應註解處理模板介面 {@link org.xutils.http.app.ResponseParser} * * 示例: 檢視 org.xutils.sample.http 包裡的程式碼 */ BaiduParams params =newBaiduParams();
params.wd ="xUtils";
// 有上傳檔案時使用multipart表單, 否則上傳原始檔案流.// params.setMultipart(true);// 上傳檔案方式 1// params.uploadFile = new File("/sdcard/test.txt");// 上傳檔案方式 2// params.addBodyParameter("uploadFile", new File("/sdcard/test.txt"));Callback.Cancelable cancelable
= x.http().get(params,
/** * 1. callback的泛型: * callback引數預設支援的泛型型別參見{@link org.xutils.http.loader.LoaderFactory}, * 例如: 指定泛型為File則可實現檔案下載, 使用params.setSaveFilePath(path)指定檔案儲存的全路徑. * 預設支援斷點續傳(採用了檔案鎖和尾端校驗續傳檔案的一致性). * 其他常用型別可以自己在LoaderFactory中註冊, * 也可以使用{@link org.xutils.http.annotation.HttpResponse} * 將註解HttpResponse加到自定義返回值型別上, 實現自定義ResponseParser介面來統一轉換. * 如果返回值是json形式, 那麼利用第三方的json工具將十分容易定義自己的ResponseParser. * 如示例程式碼{@link org.xutils.sample.http.BaiduResponse}, 可直接使用BaiduResponse作為 * callback的泛型. * * 2. callback的組合: * 可以用基類或介面組合個種類的Callback, 見{@link org.xutils.common.Callback}. * 例如: * a. 組合使用CacheCallback將使請求檢測快取或將結果存入快取(僅GET請求生效). * b. 組合使用PrepareCallback的prepare方法將為callback提供一次後臺執行耗時任務的機會, * 然後將結果給onCache或onSuccess. * c. 組合使用ProgressCallback將提供進度回撥. * ...(可參考{@link org.xutils.image.ImageLoader} * 或 示例程式碼中的 {@link org.xutils.sample.download.DownloadCallback}) * * 3. 請求過程攔截或記錄日誌: 參考 {@link org.xutils.http.app.RequestTracker} * * 4. 請求Header獲取: 參考 {@link org.xutils.http.app.RequestInterceptListener} * * 5. 其他(執行緒池, 超時, 重定向, 重試, 代理等): 參考 {@link org.xutils.http.RequestParams} * **/newCallback.CommonCallback<String>() {
@OverridepublicvoidonSuccess(Stringresult) {
Toast.makeText(x.app(), result, Toast.LENGTH_LONG).show();
}
@OverridepublicvoidonError(Throwableex, booleanisOnCallback) {
//Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();if (ex instanceofHttpException) { // 網路錯誤HttpException httpEx = (HttpException) ex;
int responseCode = httpEx.getCode();
String responseMsg = httpEx.getMessage();
String errorResult = httpEx.getResult();
// ...
} else { // 其他錯誤// ...
}
Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
}
@OverridepublicvoidonCancelled(CancelledExceptioncex) {
Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
}
@OverridepublicvoidonFinished() {
}
});
// cancelable.cancel(); // 取消請求
簡單版本
RequestParams params =newRequestParams("https://www.baidu.com/s");
params.setSslSocketFactory(...); // 設定ssl
params.addQueryStringParameter("wd", "xUtils");
x.http().get(params, newCallback.CommonCallback<String>() {
@OverridepublicvoidonSuccess(Stringresult) {
Toast.makeText(x.app(), result, Toast.LENGTH_LONG).show();
}
@OverridepublicvoidonError(Throwableex, booleanisOnCallback) {
Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
}
@OverridepublicvoidonCancelled(CancelledExceptioncex) {
Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
}
@OverridepublicvoidonFinished() {
}
});
帶有快取的請求示例:
BaiduParams params =newBaiduParams();
params.wd ="xUtils";
// 預設快取存活時間, 單位:毫秒.(如果服務沒有返回有效的max-age或Expires)
params.setCacheMaxAge(1000*60);
Callback.Cancelable cancelable
// 使用CacheCallback, xUtils將為該請求快取資料.= x.http().get(params, newCallback.CacheCallback<String>() {
privateboolean hasError =false;
privateString result =null;
@OverridepublicbooleanonCache(Stringresult) {
// 得到快取資料, 快取過期後不會進入這個方法.// 如果服務端沒有返回過期時間, 參考params.setCacheMaxAge(maxAge)方法.//// * 客戶端會根據服務端返回的 header 中 max-age 或 expires 來確定本地快取是否給 onCache 方法.// 如果服務端沒有返回 max-age 或 expires, 那麼快取將一直儲存, 除非這裡自己定義了返回false的// 邏輯, 那麼xUtils將請求新資料, 來覆蓋它.//// * 如果信任該快取返回 true, 將不再請求網路;// 返回 false 繼續請求網路, 但會在請求頭中加上ETag, Last-Modified等資訊,// 如果服務端返回304, 則表示資料沒有更新, 不繼續載入資料.//this.result = result;
returnfalse; // true: 信任快取資料, 不在發起網路請求; false不信任快取資料.
}
@OverridepublicvoidonSuccess(Stringresult) {
// 注意: 如果服務返回304或 onCache 選擇了信任快取, 這裡將不會被呼叫,// 但是 onFinished 總會被呼叫.this.result = result;
}
@OverridepublicvoidonError(Throwableex, booleanisOnCallback) {
hasError =true;
Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
if (ex instanceofHttpException) { // 網路錯誤HttpException httpEx = (HttpException) ex;
int responseCode = httpEx.getCode();
String responseMsg = httpEx.getMessage();
String errorResult = httpEx.getResult();
// ...
} else { // 其他錯誤// ...
}
}
@OverridepublicvoidonCancelled(CancelledExceptioncex) {
Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
}
@OverridepublicvoidonFinished() {
if (!hasError && result !=null) {
// 成功獲取資料Toast.makeText(x.app(), result, Toast.LENGTH_LONG).show();
}
}
});
繫結圖片
x.image().bind(imageView, url, imageOptions);
// assets file
x.image().bind(imageView, "assets://test.gif", imageOptions);
// local file
x.image().bind(imageView, newFile("/sdcard/test.gif").toURI().toString(), imageOptions);
x.image().bind(imageView, "/sdcard/test.gif", imageOptions);
x.image().bind(imageView, "file:///sdcard/test.gif", imageOptions);
x.image().bind(imageView, "file:/sdcard/test.gif", imageOptions);
x.image().bind(imageView, url, imageOptions, newCallback.CommonCallback<Drawable>() {...});
x.image().loadDrawable(url, imageOptions, newCallback.CommonCallback<Drawable>() {...});
x.image().loadFile(url, imageOptions, newCallback.CommonCallback<File>() {...});
檢視原始碼:
主要類x.class
這個類為任務控制中心, http, image, db, view注入等介面的入口. 需要在在application的onCreate中初始化: x.Ext.init(this);
作者把所有的入口全放到x.class 類中。內部靜態類 Ext來管理和建立幾個manager物件(httpManager ImageManager 等 全為介面)
我查了詞典。Ext 翻譯過來有 提取 擴充套件 外部的意思。
**
* Created by wyouflf on 15/6/10.
* 任務控制中心, http, image, db, view注入等介面的入口.
* 需要在在application的onCreate中初始化: x.Ext.init(this);
*/
public final class x {
...
public static TaskController task() {
return Ext.taskController;
}
public static HttpManager http() {...}
public static ImageManager image() {...}
public static ViewInjector view(){...}
public static DbManager getDb(DbManager.DaoConfig daoConfig){...}
public static class Ext {
private static boolean debug;
private static Application app;
private static TaskController taskController;
private static HttpManager httpManager;
private static ImageManager imageManager;
private static ViewInjector viewInjector;
private Ext() {
}
static {
TaskControllerImpl.registerInstance();
// 預設信任所有https域名
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
}
public static void init(Application app) {
if (Ext.app == null) {
Ext.app = app;
}
}
...
}
private static class MockApplication extends Application {
public MockApplication(Context baseContext) {
this.attachBaseContext(baseContext);
}
}
}
在x.class中 ,除去幾個應用的方法。我發現了TaskController 這個物件。從字面上理解應該是task控制類。我們發現TaskController 是一個介面。並且和他的實現類在common包下面,所有task相關的應該xutils3中通用的一個模組或者實現方式
檢視TaskController和TaskControllerImpl發現 這是task管理的一個控制類。
TaskController.class
/**
* Created by wyouflf on 15/6/11.
* 任務管理介面
*/
public interface TaskController {
/**
* 在UI執行緒執行runnable.
* 如果已在UI執行緒, 則直接執行.
*
* @param runnable
*/
void autoPost(Runnable runnable);
/**
* 在UI執行緒執行runnable.
* post到msg queue.
*
* @param runnable
*/
void post(Runnable runnable);
/**
* 在UI執行緒執行runnable.
*
* @param runnable
* @param delayMillis 延遲時間(單位毫秒)
*/
void postDelayed(Runnable runnable, long delayMillis);
/**
* 在後臺執行緒執行runnable
*
* @param runnable
*/
void run(Runnable runnable);
/**
* 移除未執行的runnable
*
* @param runnable
*/
void removeCallbacks(Runnable runnable);
/**
* 開始一個非同步任務
*
* @param task
* @param <T>
* @return
*/
<T> AbsTask<T> start(AbsTask<T> task);
/**
* 同步執行一個任務
*
* @param task
* @param <T>
* @return
* @throws Throwable
*/
<T> T startSync(AbsTask<T> task) throws Throwable;
/**
* 批量執行非同步任務
*
* @param groupCallback
* @param tasks
* @param <T>
* @return
*/
<T extends AbsTask<?>> Callback.Cancelable startTasks(Callback.GroupCallback<T> groupCallback, T... tasks);
}
TaskControllerImpl.class 在實現類中我們發現。它的作用應該是1.回撥函式發回主執行緒。2.目標task的dobackground方法執行
@Override
public void autoPost(Runnable runnable) {
if (runnable == null) return;
if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
runnable.run();
} else {
TaskProxy.sHandler.post(runnable);
}
}
/**
* run task
*
* @param task
* @param <T>
* @return
*/
@Override
public <T> AbsTask<T> start(AbsTask<T> task) {
TaskProxy<T> proxy = null;
if (task instanceof TaskProxy) {
proxy = (TaskProxy<T>) task;
} else {
proxy = new TaskProxy<T>(task);
}
try {
proxy.doBackground();
} catch (Throwable ex) {
LogUtil.e(ex.getMessage(), ex);
}
return proxy;
}
@SuppressWarnings("unchecked")
@Override
public <T extends AbsTask<?>> Callback.Cancelable startTasks(
final Callback.GroupCallback<T> groupCallback, final T... tasks) {
if (tasks == null) {
throw new IllegalArgumentException("task must not be null");
}
final Runnable callIfOnAllFinished = new Runnable() {
private final int total = tasks.length;
private final AtomicInteger count = new AtomicInteger(0);
@Override
public void run() {
if (count.incrementAndGet() == total) {
if (groupCallback != null) {
groupCallback.onAllFinished();
}
}
}
};
for (final T task : tasks) {
start(new TaskProxy(task) {
@Override
protected void onSuccess(Object result) {
super.onSuccess(result);
post(new Runnable() {
@Override
public void run() {
if (groupCallback != null) {
groupCallback.onSuccess(task);
}
}
});
}
@Override
protected void onCancelled(final Callback.CancelledException cex) {
super.onCancelled(cex);
post(new Runnable() {
@Override
public void run() {
if (groupCallback != null) {
groupCallback.onCancelled(task, cex);
}
}
});
}
@Override
protected void onError(final Throwable ex, final boolean isCallbackError) {
super.onError(ex, isCallbackError);
post(new Runnable() {
@Override
public void run() {
if (groupCallback != null) {
groupCallback.onError(task, ex, isCallbackError);
}
}
});
}
@Override
protected void onFinished() {
super.onFinished();
post(new Runnable() {
@Override
public void run() {
if (groupCallback != null) {
groupCallback.onFinished(task);
}
callIfOnAllFinished.run();
}
});
}
});
}
return new Callback.Cancelable() {
@Override
public void cancel() {
for (T task : tasks) {
task.cancel();
}
}
@Override
public boolean isCancelled() {
boolean isCancelled = true;
for (T task : tasks) {
if (!task.isCancelled()) {
isCancelled = false;
}
}
return isCancelled;
}
};
}
Task相關
在TaskControllerImpl中出現了倆個類AysTask.class 和TaskProxy.class
AysTask 非同步任務基類
AysTask是非同步任務的基類並且是個抽象類。實現了callback的取消介面
繼承AysTask 必須要複寫三個方法doBackground,onSuccess,onError
/**
* Created by wyouflf on 15/6/5.
* 非同步任務基類
*
* @param <ResultType>
*/
public abstract class AbsTask<ResultType> implements Callback.Cancelable {
private TaskProxy taskProxy = null;
private final Callback.Cancelable cancelHandler;
private volatile boolean isCancelled = false;
private volatile State state = State.IDLE;
private ResultType result;
...
protected abstract ResultType doBackground() throws Throwable;
protected abstract void onSuccess(ResultType result);
protected abstract void onError(Throwable ex, boolean isCallbackError);
...
@Override//通用的非同步載入的cancel方法
public final synchronized void cancel() {
if (!this.isCancelled) {
this.isCancelled = true;
cancelWorks();
if (cancelHandler != null && !cancelHandler.isCancelled()) {
cancelHandler.cancel();
}
if (this.state == State.WAITING || (this.state == State.STARTED && isCancelFast())) {
if (taskProxy != null) {
taskProxy.onCancelled(new Callback.CancelledException("cancelled by user"));
taskProxy.onFinished();
} else if (this instanceof TaskProxy) {
this.onCancelled(new Callback.CancelledException("cancelled by user"));
this.onFinished();
}
}
}
}
@Override
public final boolean isCancelled() {
return isCancelled || state == State.CANCELLED ||
(cancelHandler != null && cancelHandler.isCancelled());
}
public enum State {//執行緒的幾個狀態 大學裡應該學過
IDLE(0), WAITING(1), STARTED(2), SUCCESS(3), CANCELLED(4), ERROR(5);
private final int value;
private State(int value) {
this.value = value;
}
public int value() {
return value;
}
}
}
註釋: volatile:就像大家更熟悉的const一樣,volatile是一個型別修飾符(type specifier)。它是被設計用來修飾被不同執行緒訪問和修改的變數。如果不加入volatile,基本上會導致這樣的結果:要麼無法編寫多執行緒程式,要麼編譯器失去大量優化的機會。(ps:寫這篇部落格之前根本不知道這個東西)
- TaskProxy
Taskproxy 非同步任務的代理類。這裡面有兩個重要的成員變數
handle 和PriorityExecutor 。
在程式碼
private InternalHandler() {
super(Looper.getMainLooper());
}
看到 handle 是依靠MainThread 建立的。所有最後傳送出去的message都會被 Mainthread接受。
PriorityExecutor 為執行緒池。這裡不多講了。
/**
* 非同步任務的代理類(僅在task包內可用)
*
* @param <ResultType>
*/
/*package*/ class TaskProxy<ResultType> extends AbsTask<ResultType> {
/*package*/ static final InternalHandler sHandler = new InternalHandler();
/*package*/ static final PriorityExecutor sDefaultExecutor = new PriorityExecutor(true);
private final AbsTask<ResultType> task;
private final Executor executor;
private volatile boolean callOnCanceled = false;
private volatile boolean callOnFinished = false;
/*package*/ TaskProxy(AbsTask<ResultType> task) {
super(task);
this.task = task;
this.task.setTaskProxy(this);
this.setTaskProxy(null);
Executor taskExecutor = task.getExecutor();
if (taskExecutor == null) {
taskExecutor = sDefaultExecutor;
}
this.executor = taskExecutor;
}
@Override
protected final ResultType doBackground() throws Throwable {
this.onWaiting();
PriorityRunnable runnable = new PriorityRunnable(
task.getPriority(),
new Runnable() {
@Override
public void run() {
try {
// 等待過程中取消
if (callOnCanceled || TaskProxy.this.isCancelled()) {
throw new Callback.CancelledException("");
}
// start running
TaskProxy.this.onStarted();
if (TaskProxy.this.isCancelled()) { // 開始時取消
throw new Callback.CancelledException("");
}
// 執行task, 得到結果.
task.setResult(task.doBackground());
TaskProxy.this.setResult(task.getResult());
// 未在doBackground過程中取消成功
if (TaskProxy.this.isCancelled()) {
throw new Callback.CancelledException("");
}
// 執行成功
TaskProxy.this.onSuccess(task.getResult());
} catch (Callback.CancelledException cex) {
TaskProxy.this.onCancelled(cex);
} catch (Throwable ex) {
TaskProxy.this.onError(ex, false);
} finally {
TaskProxy.this.onFinished();
}
}
});
this.executor.execute(runnable);
return null;
}
@Override
protected void onSuccess(ResultType result) {
this.setState(State.SUCCESS);
sHandler.obtainMessage(MSG_WHAT_ON_SUCCESS, this).sendToTarget();
}
@Override
/*package*/ final void setState(State state) {
super.setState(state);
this.task.setState(state);
}
// ########################### inner type #############################
private static class ArgsObj {
final TaskProxy taskProxy;
final Object[] args;
public ArgsObj(TaskProxy taskProxy, Object... args) {
this.taskProxy = taskProxy;
this.args = args;
}
}
private final static int MSG_WHAT_BASE = 1000000000;
private final static int MSG_WHAT_ON_WAITING = MSG_WHAT_BASE + 1;
private final static int MSG_WHAT_ON_START = MSG_WHAT_BASE + 2;
private final static int MSG_WHAT_ON_SUCCESS = MSG_WHAT_BASE + 3;
private final static int MSG_WHAT_ON_ERROR = MSG_WHAT_BASE + 4;
private final static int MSG_WHAT_ON_UPDATE = MSG_WHAT_BASE + 5;
private final static int MSG_WHAT_ON_CANCEL = MSG_WHAT_BASE + 6;
private final static int MSG_WHAT_ON_FINISHED = MSG_WHAT_BASE + 7;
/*package*/ final static class InternalHandler extends Handler {
private InternalHandler() {
super(Looper.getMainLooper());
}
@Override
@SuppressWarnings("unchecked")
public void handleMessage(Message msg) {
if (msg.obj == null) {
throw new IllegalArgumentException("msg must not be null");
}
.......
}
}
現在主要看 handle的處理方法handleMessage:
在方法中 會得到一個TaskProxy代理物件。
TaskProxy.task為構建物件時候傳遞進來的一個AbsTask實現類。該實現類裡面會實現一些 成功或失敗的方法。 然後 handle會通過what來區別和呼叫onSuccess ,onError
@Override
@SuppressWarnings("unchecked")
public void handleMessage(Message msg) {
if (msg.obj == null) {
throw new IllegalArgumentException("msg must not be null");
}
TaskProxy taskProxy = null;
Object[] args = null;
if (msg.obj instanceof TaskProxy) {
taskProxy = (TaskProxy) msg.obj;
} else if (msg.obj instanceof ArgsObj) {
ArgsObj argsObj = (ArgsObj) msg.obj;
taskProxy = argsObj.taskProxy;
args = argsObj.args;
}
if (taskProxy == null) {
throw new RuntimeException("msg.obj not instanceof TaskProxy");
}
try {
switch (msg.what) {
case MSG_WHAT_ON_WAITING: {
taskProxy.task.onWaiting();
break;
}
case MSG_WHAT_ON_START: {
taskProxy.task.onStarted();
break;
}
case MSG_WHAT_ON_SUCCESS: {
taskProxy.task.onSuccess(taskProxy.getResult());
break;
}
case MSG_WHAT_ON_ERROR: {
assert args != null;
Throwable throwable = (Throwable) args[0];
LogUtil.d(throwable.getMessage(), throwable);
taskProxy.task.onError(throwable, false);
break;
}
case MSG_WHAT_ON_UPDATE: {
taskProxy.task.onUpdate(msg.arg1, args);
break;
}
case MSG_WHAT_ON_CANCEL: {
if (taskProxy.callOnCanceled) return;
taskProxy.callOnCanceled = true;
assert args != null;
taskProxy.task.onCancelled((org.xutils.common.Callback.CancelledException) args[0]);
break;
}
case MSG_WHAT_ON_FINISHED: {
if (taskProxy.callOnFinished) return;
taskProxy.callOnFinished = true;
taskProxy.task.onFinished();
break;
}
default: {
break;
}
}
} catch (Throwable ex) {
taskProxy.setState(State.ERROR);
if (msg.what != MSG_WHAT_ON_ERROR) {
taskProxy.task.onError(ex, true);
} else if (x.isDebug()) {
throw new RuntimeException(ex);
}
}
}