歡迎轉載,但請保留作者鏈接:http://www.lxweimin.com/p/b7fec0545368
在閱讀本文之前,你需要了解Handler作為Android中的線程間通信機制究竟是如何運作的,可以參考Android 異步消息處理機制 讓你深入理解 Looper、Handler、Message三者關系
源碼
/**
* A helper class to help make handling asynchronous {@link ContentResolver}
* queries easier.
*/
public abstract class AsyncQueryHandler extends Handler {
private static final String TAG = "AsyncQuery";
private static final boolean localLOGV = false;
private static final int EVENT_ARG_QUERY = 1;
private static final int EVENT_ARG_INSERT = 2;
private static final int EVENT_ARG_UPDATE = 3;
private static final int EVENT_ARG_DELETE = 4;
/* package */ final WeakReference<ContentResolver> mResolver;
private static Looper sLooper = null;
private Handler mWorkerThreadHandler;
protected static final class WorkerArgs {
public Uri uri;
public Handler handler;
public String[] projection;
public String selection;
public String[] selectionArgs;
public String orderBy;
public Object result;
public Object cookie;
public ContentValues values;
}
protected class WorkerHandler extends Handler {
public WorkerHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
final ContentResolver resolver = mResolver.get();
if (resolver == null) return;
WorkerArgs args = (WorkerArgs) msg.obj;
int token = msg.what;
int event = msg.arg1;
switch (event) {
case EVENT_ARG_QUERY:
Cursor cursor;
try {
cursor = resolver.query(args.uri, args.projection,
args.selection, args.selectionArgs,
args.orderBy);
// Calling getCount() causes the cursor window to be filled,
// which will make the first access on the main thread a lot faster.
if (cursor != null) {
cursor.getCount();
}
} catch (Exception e) {
Log.w(TAG, "Exception thrown during handling EVENT_ARG_QUERY", e);
cursor = null;
}
args.result = cursor;
break;
case EVENT_ARG_INSERT:
args.result = resolver.insert(args.uri, args.values);
break;
case EVENT_ARG_UPDATE:
args.result = resolver.update(args.uri, args.values, args.selection,
args.selectionArgs);
break;
case EVENT_ARG_DELETE:
args.result = resolver.delete(args.uri, args.selection, args.selectionArgs);
break;
}
// passing the original token value back to the caller
// on top of the event values in arg1.
Message reply = args.handler.obtainMessage(token);
reply.obj = args;
reply.arg1 = msg.arg1;
if (localLOGV) {
Log.d(TAG, "WorkerHandler.handleMsg: msg.arg1=" + msg.arg1
+ ", reply.what=" + reply.what);
}
reply.sendToTarget();
}
}
public AsyncQueryHandler(ContentResolver cr) {
super();
mResolver = new WeakReference<ContentResolver>(cr);
synchronized (AsyncQueryHandler.class) {
if (sLooper == null) {
HandlerThread thread = new HandlerThread("AsyncQueryWorker");
thread.start();
sLooper = thread.getLooper();
}
}
mWorkerThreadHandler = createHandler(sLooper);
}
protected Handler createHandler(Looper looper) {
return new WorkerHandler(looper);
}
/**
* This method begins an asynchronous query. When the query is done
* {@link #onQueryComplete} is called.
*
* @param token A token passed into {@link #onQueryComplete} to identify
* the query.
* @param cookie An object that gets passed into {@link #onQueryComplete}
* @param uri The URI, using the content:// scheme, for the content to
* retrieve.
* @param projection A list of which columns to return. Passing null will
* return all columns, which is discouraged to prevent reading data
* from storage that isn't going to be used.
* @param selection A filter declaring which rows to return, formatted as an
* SQL WHERE clause (excluding the WHERE itself). Passing null will
* return all rows for the given URI.
* @param selectionArgs You may include ?s in selection, which will be
* replaced by the values from selectionArgs, in the order that they
* appear in the selection. The values will be bound as Strings.
* @param orderBy How to order the rows, formatted as an SQL ORDER BY
* clause (excluding the ORDER BY itself). Passing null will use the
* default sort order, which may be unordered.
*/
public void startQuery(int token, Object cookie, Uri uri,
String[] projection, String selection, String[] selectionArgs,
String orderBy) {
// Use the token as what so cancelOperations works properly
Message msg = mWorkerThreadHandler.obtainMessage(token);
msg.arg1 = EVENT_ARG_QUERY;
WorkerArgs args = new WorkerArgs();
args.handler = this;
args.uri = uri;
args.projection = projection;
args.selection = selection;
args.selectionArgs = selectionArgs;
args.orderBy = orderBy;
args.cookie = cookie;
msg.obj = args;
mWorkerThreadHandler.sendMessage(msg);
}
/**
* Attempts to cancel operation that has not already started. Note that
* there is no guarantee that the operation will be canceled. They still may
* result in a call to on[Query/Insert/Update/Delete]Complete after this
* call has completed.
*
* @param token The token representing the operation to be canceled.
* If multiple operations have the same token they will all be canceled.
*/
public final void cancelOperation(int token) {
mWorkerThreadHandler.removeMessages(token);
}
/**
* This method begins an asynchronous insert. When the insert operation is
* done {@link #onInsertComplete} is called.
*
* @param token A token passed into {@link #onInsertComplete} to identify
* the insert operation.
* @param cookie An object that gets passed into {@link #onInsertComplete}
* @param uri the Uri passed to the insert operation.
* @param initialValues the ContentValues parameter passed to the insert operation.
*/
public final void startInsert(int token, Object cookie, Uri uri,
ContentValues initialValues) {
// Use the token as what so cancelOperations works properly
Message msg = mWorkerThreadHandler.obtainMessage(token);
msg.arg1 = EVENT_ARG_INSERT;
WorkerArgs args = new WorkerArgs();
args.handler = this;
args.uri = uri;
args.cookie = cookie;
args.values = initialValues;
msg.obj = args;
mWorkerThreadHandler.sendMessage(msg);
}
/**
* This method begins an asynchronous update. When the update operation is
* done {@link #onUpdateComplete} is called.
*
* @param token A token passed into {@link #onUpdateComplete} to identify
* the update operation.
* @param cookie An object that gets passed into {@link #onUpdateComplete}
* @param uri the Uri passed to the update operation.
* @param values the ContentValues parameter passed to the update operation.
*/
public final void startUpdate(int token, Object cookie, Uri uri,
ContentValues values, String selection, String[] selectionArgs) {
// Use the token as what so cancelOperations works properly
Message msg = mWorkerThreadHandler.obtainMessage(token);
msg.arg1 = EVENT_ARG_UPDATE;
WorkerArgs args = new WorkerArgs();
args.handler = this;
args.uri = uri;
args.cookie = cookie;
args.values = values;
args.selection = selection;
args.selectionArgs = selectionArgs;
msg.obj = args;
mWorkerThreadHandler.sendMessage(msg);
}
/**
* This method begins an asynchronous delete. When the delete operation is
* done {@link #onDeleteComplete} is called.
*
* @param token A token passed into {@link #onDeleteComplete} to identify
* the delete operation.
* @param cookie An object that gets passed into {@link #onDeleteComplete}
* @param uri the Uri passed to the delete operation.
* @param selection the where clause.
*/
public final void startDelete(int token, Object cookie, Uri uri,
String selection, String[] selectionArgs) {
// Use the token as what so cancelOperations works properly
Message msg = mWorkerThreadHandler.obtainMessage(token);
msg.arg1 = EVENT_ARG_DELETE;
WorkerArgs args = new WorkerArgs();
args.handler = this;
args.uri = uri;
args.cookie = cookie;
args.selection = selection;
args.selectionArgs = selectionArgs;
msg.obj = args;
mWorkerThreadHandler.sendMessage(msg);
}
/**
* Called when an asynchronous query is completed.
*
* @param token the token to identify the query, passed in from
* {@link #startQuery}.
* @param cookie the cookie object passed in from {@link #startQuery}.
* @param cursor The cursor holding the results from the query.
*/
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
// Empty
}
/**
* Called when an asynchronous insert is completed.
*
* @param token the token to identify the query, passed in from
* {@link #startInsert}.
* @param cookie the cookie object that's passed in from
* {@link #startInsert}.
* @param uri the uri returned from the insert operation.
*/
protected void onInsertComplete(int token, Object cookie, Uri uri) {
// Empty
}
/**
* Called when an asynchronous update is completed.
*
* @param token the token to identify the query, passed in from
* {@link #startUpdate}.
* @param cookie the cookie object that's passed in from
* {@link #startUpdate}.
* @param result the result returned from the update operation
*/
protected void onUpdateComplete(int token, Object cookie, int result) {
// Empty
}
/**
* Called when an asynchronous delete is completed.
*
* @param token the token to identify the query, passed in from
* {@link #startDelete}.
* @param cookie the cookie object that's passed in from
* {@link #startDelete}.
* @param result the result returned from the delete operation
*/
protected void onDeleteComplete(int token, Object cookie, int result) {
// Empty
}
@Override
public void handleMessage(Message msg) {
WorkerArgs args = (WorkerArgs) msg.obj;
if (localLOGV) {
Log.d(TAG, "AsyncQueryHandler.handleMessage: msg.what=" + msg.what
+ ", msg.arg1=" + msg.arg1);
}
int token = msg.what;
int event = msg.arg1;
// pass token back to caller on each callback.
switch (event) {
case EVENT_ARG_QUERY:
onQueryComplete(token, args.cookie, (Cursor) args.result);
break;
case EVENT_ARG_INSERT:
onInsertComplete(token, args.cookie, (Uri) args.result);
break;
case EVENT_ARG_UPDATE:
onUpdateComplete(token, args.cookie, (Integer) args.result);
break;
case EVENT_ARG_DELETE:
onDeleteComplete(token, args.cookie, (Integer) args.result);
break;
}
}
}
背景
/**
* A helper class to help make handling asynchronous {@link ContentResolver}
* queries easier.
*/
這是07年的代碼,從最開頭的類注釋來看,寫這個helper類的目的是用于簡化ContentResolver異步查詢。出于歷史因素,你可以在某些Android應用——比如Dialer——源碼中看到它的身影。不過就實際而言,后來出現的Loader在可代替的情況下比它更好用。
雖然如此,作為官方范例,在Handler的使用上還是有著不少學習之處。
解讀
先看構造方法:
public AsyncQueryHandler(ContentResolver cr) {
super();
mResolver = new WeakReference<ContentResolver>(cr);
synchronized (AsyncQueryHandler.class) {
if (sLooper == null) {
HandlerThread thread = new HandlerThread("AsyncQueryWorker");
thread.start();
sLooper = thread.getLooper();
}
}
mWorkerThreadHandler = createHandler(sLooper);
}
它做了這樣幾件事:
- super()調用父親構造方法,令此AsyncQueryHandler工作在主線程中(參見Handler源碼,其中有mLooper = Looper.myLooper();)。
- 將ContentResolver作為弱引用持有
- 在類同步語句塊中,如果由static修飾的sLooper為null,創建一個工作線程thread,然后得到sLooper的值。
參考資料:Java 多線程(六) synchronized關鍵字詳解 - 通過sLooper,創建在工作線程中工作的mWorkerThreadHandler 。因為是同一個sLooper,所以不同AsyncQueryHandler實例的mWorkerThreadHandler 工作在同一個工作線程中。
HandlerThread專門設計用于與Handler協同工作,從設計角度而言,這樣關系緊密的兩個類,要么用A持有B的方式擴展使用,要么就反過來。這里是由Handler持有HandlerThread,與HandlerThread持有Handler的方式相比各有優缺點。
這里封裝的具體操作無非是増刪改查,我們看一種就好:
/**
* This method begins an asynchronous query. When the query is done
* {@link #onQueryComplete} is called.
*
* @param token A token passed into {@link #onQueryComplete} to identify
* the query.
* @param cookie An object that gets passed into {@link #onQueryComplete}
* @param uri The URI, using the content:// scheme, for the content to
* retrieve.
* @param projection A list of which columns to return. Passing null will
* return all columns, which is discouraged to prevent reading data
* from storage that isn't going to be used.
* @param selection A filter declaring which rows to return, formatted as an
* SQL WHERE clause (excluding the WHERE itself). Passing null will
* return all rows for the given URI.
* @param selectionArgs You may include ?s in selection, which will be
* replaced by the values from selectionArgs, in the order that they
* appear in the selection. The values will be bound as Strings.
* @param orderBy How to order the rows, formatted as an SQL ORDER BY
* clause (excluding the ORDER BY itself). Passing null will use the
* default sort order, which may be unordered.
*/
public void startQuery(int token, Object cookie, Uri uri,
String[] projection, String selection, String[] selectionArgs,
String orderBy) {
// Use the token as what so cancelOperations works properly
Message msg = mWorkerThreadHandler.obtainMessage(token);
msg.arg1 = EVENT_ARG_QUERY;
WorkerArgs args = new WorkerArgs();
args.handler = this;
args.uri = uri;
args.projection = projection;
args.selection = selection;
args.selectionArgs = selectionArgs;
args.orderBy = orderBy;
args.cookie = cookie;
msg.obj = args;
mWorkerThreadHandler.sendMessage(msg);
}
注釋已經十分詳細,做的事情也十分簡單,用obtainMessage()
從循環池中拿出一個Message,放上表示動作的標志位msg.arg1 = EVENT_ARG_QUERY;
,然后構造一個專門用于放數據的靜態內部類WorkerArgs ,傳入的參數全部放入其中,再作為Object傳給Messagemsg.obj = args;
,最后是發出MessagemWorkerThreadHandler.sendMessage(msg);
。
再看下WorkerThreadHandler是如何工作的:
protected class WorkerHandler extends Handler {
public WorkerHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
final ContentResolver resolver = mResolver.get();
if (resolver == null) return;
WorkerArgs args = (WorkerArgs) msg.obj;
int token = msg.what;
int event = msg.arg1;
switch (event) {
case EVENT_ARG_QUERY:
Cursor cursor;
try {
cursor = resolver.query(args.uri, args.projection,
args.selection, args.selectionArgs,
args.orderBy);
// Calling getCount() causes the cursor window to be filled,
// which will make the first access on the main thread a lot faster.
if (cursor != null) {
cursor.getCount();
}
} catch (Exception e) {
Log.w(TAG, "Exception thrown during handling EVENT_ARG_QUERY", e);
cursor = null;
}
args.result = cursor;
break;
case EVENT_ARG_INSERT:
args.result = resolver.insert(args.uri, args.values);
break;
case EVENT_ARG_UPDATE:
args.result = resolver.update(args.uri, args.values, args.selection,
args.selectionArgs);
break;
case EVENT_ARG_DELETE:
args.result = resolver.delete(args.uri, args.selection, args.selectionArgs);
break;
}
// passing the original token value back to the caller
// on top of the event values in arg1.
Message reply = args.handler.obtainMessage(token);
reply.obj = args;
reply.arg1 = msg.arg1;
if (localLOGV) {
Log.d(TAG, "WorkerHandler.handleMsg: msg.arg1=" + msg.arg1
+ ", reply.what=" + reply.what);
}
reply.sendToTarget();
}
}
根據傳來的msg.arg1;
判定是什么事件,處理后通過args.handler即AsyncQueryHandler本身構造回復用的Message,傳入數據的同時reply.obj = args;
繼續傳入標志位reply.arg1 = msg.arg1;
,然后回復即可。
注意這里告訴了我們一個使用Cursor時提速的技巧:
// Calling getCount() causes the cursor window to be filled,
// which will make the first access on the main thread a lot faster.
if (cursor != null) {
cursor.getCount();
}
最后就是主線程中的處理了:
@Override
public void handleMessage(Message msg) {
WorkerArgs args = (WorkerArgs) msg.obj;
if (localLOGV) {
Log.d(TAG, "AsyncQueryHandler.handleMessage: msg.what=" + msg.what
+ ", msg.arg1=" + msg.arg1);
}
int token = msg.what;
int event = msg.arg1;
// pass token back to caller on each callback.
switch (event) {
case EVENT_ARG_QUERY:
onQueryComplete(token, args.cookie, (Cursor) args.result);
break;
case EVENT_ARG_INSERT:
onInsertComplete(token, args.cookie, (Uri) args.result);
break;
case EVENT_ARG_UPDATE:
onUpdateComplete(token, args.cookie, (Integer) args.result);
break;
case EVENT_ARG_DELETE:
onDeleteComplete(token, args.cookie, (Integer) args.result);
break;
}
}
通過標志位判定,來進行増刪改查后的回調處理。
本篇至此結束,下次見。