博文出處:探究Android異步消息的處理之Handler詳解,歡迎大家關注我的博客,謝謝!
在學習Android的路上,大家肯定會遇到異步消息處理,Android提供給我們一個類來處理相關的問題,那就是Handler。相信大家大多都用過Handler了,下面我們就來看看Handler最簡單的用法:
public class FirstActivity extends AppCompatActivity {
public static final String TAG = "FirstActivity";
private static Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
Log.i(TAG, "handler receive msg.what = " + msg.what);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
new Thread(new Runnable() {
@Override
public void run() {
//這里做相關操作
handler.sendEmptyMessage(0);
}
}).start();
}
}
上面代碼實現了在子線程中發出一個消息,然后在主線程中接收消息。Handler其他類似的用法在這就不過多敘述了。下面我們來看看Handler到底是怎么實現異步消息處理的吧!
先來看看我們new一個Handler的對象到底發生了什么(只截取了關鍵源碼):
public Handler() {
this(null, false);
}
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
可以看到我們平常寫的 new Handler();其實是調用了另外一個構造方法,并且判斷了mLooper是不是為空,為空則拋出一個異常"Can't create handler inside thread that has not called Looper.prepare()",mLooper其實是一個Looper類的成員變量,官方文檔上對Looper類的解釋是 Class used to run a message loop for a thread.也就是說Looper用于在一個線程中傳遞message的。 然后我們根據異常的提示知道要在new一個Handler的對象之前必須
先調用Looper.prepare()。那接下來就只能先去看看Looper.prepare()方法了:
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper; // guarded by Looper.class
final MessageQueue mQueue;
final Thread mThread;
private Printer mLogging;
/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(msg);
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}
msg.recycleUnchecked();
}
}
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
prepare()方法就是將一個sThreadLocal和新建的Looper對象相綁定,同時mQueue成員變量也創建了新的MessageQueue對象,MessageQueue這個類就是用于存儲Message的隊列。在prepare()方法的注釋上寫著在調用prepare()方法之后還要調用loop()方法,我們再看loop方法,可以看到方法里寫了一個for的死循環,主要用于在MessageQueue里不斷地去取Message,如果msg為空,則阻塞;不然會調用msg.target.dispatchMessage(msg)這個方法。dispatchMessage()這個方法我會在后面講解,先暫時放一邊不管。
好了,捋一捋思路,當你在新建一個Handler對象時,要先確保調用了Looper.prepare()方法,然后調用Looper.loop()方法讓MessageQueue這個隊列“動”起來。這樣你就成功地創建了一個Handler的對象。然后我們再使用Handler的sendMessage系列方法來發送一個消息。下面我們就來看看sendMessage系列方法里到底干了什么:
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
為什么我就貼出一個方法呢?這是因為Handler一系列的sendMessage方法基本上最后都是調用了sendMessageAtTime這個方法。從源碼中我們看到主要就是干了把Message加入隊列這個事,并把當前的Handler對象賦給了msg的target。再聯系上面的Looper.loop方法,我們大概就懂了。好了,我們回過頭來看看上面的msg.target.dispatchMessage(msg)主要的功能。其實就是調用了Handler的dispatchMessage方法:
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
我們看到了一行熟悉的代碼:handleMessage(msg),這不正是我們再創建Handler對象時重寫的那個方法么!好了,這一切的邏輯我們似乎已經搞清了:首先調用Looper.prepare()創建一個Looper對象,然后handler發送消息后把消息加入到MessageQueue里,因為之前調用了Looper.loop(),所以MessageQueue在不斷地做出隊的操作,然后再根據message的target變量分發消息,回到handler的handleMessage()方法。
也許有人會有疑問了,為什么在主線程中創建Handler對象可以直接使用而不需要調用Looper.prepare()和Looper.loop()兩個方法呢?這是因為在ActivityThread里面已經調用了,下面附上ActivityThread的源碼:
/**
* This manages the execution of the main thread in an
* application process, scheduling and executing activities,
* broadcasts, and other operations on it as the activity
* manager requests.
*
* {@hide}
*/
public final class ActivityThread {
static ContextImpl mSystemContext = null;
static IPackageManager sPackageManager;
// 創建ApplicationThread實例,以接收AMS指令并執行
final ApplicationThread mAppThread = new ApplicationThread();
final Looper mLooper = Looper.myLooper();
final H mH = new H();
final HashMap<IBinder, ActivityClientRecord> mActivities
= new HashMap<IBinder, ActivityClientRecord>();
// List of new activities (via ActivityRecord.nextIdle) that should
// be reported when next we idle.
ActivityClientRecord mNewActivities = null;
// Number of activities that are currently visible on-screen.
int mNumVisibleActivities = 0;
final HashMap<IBinder, Service> mServices
= new HashMap<IBinder, Service>();
Application mInitialApplication;
final ArrayList<Application> mAllApplications
= new ArrayList<Application>();
static final ThreadLocal<ActivityThread> sThreadLocal = new ThreadLocal<ActivityThread>();
Instrumentation mInstrumentation;
static Handler sMainThreadHandler; // set once in main()
static final class ActivityClientRecord {
IBinder token;
int ident;
Intent intent;
Bundle state;
Activity activity;
Window window;
Activity parent;
String embeddedID;
Activity.NonConfigurationInstances lastNonConfigurationInstances;
boolean paused;
boolean stopped;
boolean hideForNow;
Configuration newConfig;
Configuration createdConfig;
ActivityClientRecord nextIdle;
String profileFile;
ParcelFileDescriptor profileFd;
boolean autoStopProfiler;
ActivityInfo activityInfo;
CompatibilityInfo compatInfo;
LoadedApk packageInfo; //包信息,通過調用ActivityThread.getPapckageInfo而獲得
List<ResultInfo> pendingResults;
List<Intent> pendingIntents;
boolean startsNotResumed;
boolean isForward;
int pendingConfigChanges;
boolean onlyLocalRequest;
View mPendingRemoveWindow;
WindowManager mPendingRemoveWindowManager;
...
}
private class ApplicationThread extends ApplicationThreadNative {
private void updatePendingConfiguration(Configuration config) {
synchronized (mPackages) {
if (mPendingConfiguration == null ||
mPendingConfiguration.isOtherSeqNewer(config)) {
mPendingConfiguration = config;
}
}
}
public final void schedulePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges) {
queueOrSendMessage(
finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
token,
(userLeaving ? 1 : 0),
configChanges);
}
// we use token to identify this activity without having to send the
// activity itself back to the activity manager. (matters more with ipc)
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
Bundle state, List<ResultInfo> pendingResults,
List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,
String profileName, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
ActivityClientRecord r = new ActivityClientRecord();
r.token = token;
r.ident = ident;
r.intent = intent;
r.activityInfo = info;
r.compatInfo = compatInfo;
r.state = state;
r.pendingResults = pendingResults;
r.pendingIntents = pendingNewIntents;
r.startsNotResumed = notResumed;
r.isForward = isForward;
r.profileFile = profileName;
r.profileFd = profileFd;
r.autoStopProfiler = autoStopProfiler;
updatePendingConfiguration(curConfig);
queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
}
...
}
private class H extends Handler {
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
case LAUNCH_ACTIVITY: {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
ActivityClientRecord r = (ActivityClientRecord)msg.obj;
r.packageInfo = getPackageInfoNoCheck(
r.activityInfo.applicationInfo, r.compatInfo);
handleLaunchActivity(r, null);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;
...
}
if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));
}
...
}
public static ActivityThread currentActivityThread() {
return sThreadLocal.get();
}
public static void main(String[] args) {
SamplingProfilerIntegration.start();
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
// 創建ActivityThread實例
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
AsyncTask.init();
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
}
可以看到上面的main方法里的181行和198行已經調用了prepare和loop的方法。因此在主線程中使用Handler不需要再調用prepare和loop方法了。
好了,今天該講的差不多了,就到這吧。
由于第一次寫講解源碼的博客,不便之處請大家多多包涵。有問題的可以在下面評論。