感谢您提出一个非常有趣的问题。
事实证明,UI 和主线程不一定相同。但是,正如您引用的文档中所述,这种区别仅在某些系统应用程序(作为操作系统的一部分运行的应用程序)的上下文中很重要。因此,只要您不为手机制造商构建定制ROM或定制Android,我根本不会费心去区分。
长答案:
首先我找到了将@MainThread 和@UiThread 注释引入支持库的提交:
commit 774c065affaddf66d4bec1126183435f7c663ab0
Author: Tor Norbye <tnorbye@google.com>
Date: Tue Mar 10 19:12:04 2015 -0700
Add threading annotations
These describe threading requirements for a given method,
or threading promises made to a callback.
Change-Id: I802d2415c5fa60bc687419bc2564762376a5b3ef
评论不包含与问题相关的任何信息,并且由于我没有与 Tor Norbye 的沟通渠道(叹气),所以这里没有运气。
也许这些注释正在用于 AOSP 的源代码中,我们可以从中获得一些见解?让我们搜索一下 AOSP 中任一注解的用法:
aosp $ find ./ -name *.java | xargs perl -nle 'print "in file: ".$ARGV."; match: ".$& if m{(\@MainThread|\@UiThread)(?!Test).*}'
aosp $
上述命令将在 AOSP 中的任何 .java 文件中找到任何使用 @MainThread 或 @UiThread 的情况(后面没有附加的 Test 字符串)。它什么也没找到。这里也没有运气。
所以我们需要去AOSP的源码中寻找提示。我猜我可以从Activity#runOnUiThread(Runnable)方法开始:
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
这里没有什么特别有趣的。让我们看看mUiThread 成员是如何被初始化的:
final void attach(Context context, ActivityThread aThread,
Instrumentation instr, IBinder token, int ident,
Application application, Intent intent, ActivityInfo info,
CharSequence title, Activity parent, String id,
NonConfigurationInstances lastNonConfigurationInstances,
Configuration config, String referrer, IVoiceInteractor voiceInteractor) {
attachBaseContext(context);
mFragments.attachActivity(this, mContainer, null);
mWindow = PolicyManager.makeNewWindow(this);
mWindow.setCallback(this);
mWindow.setOnWindowDismissedCallback(this);
mWindow.getLayoutInflater().setPrivateFactory(this);
if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
mWindow.setSoftInputMode(info.softInputMode);
}
if (info.uiOptions != 0) {
mWindow.setUiOptions(info.uiOptions);
}
mUiThread = Thread.currentThread();
mMainThread = aThread;
// ... more stuff here ...
}
大奖!最后两行(由于不相关而省略了其他行)是“main”和“ui”线程可能确实是不同线程的第一个迹象。
“ui”线程的概念从mUiThread = Thread.currentThread(); 这一行中可以清楚地看出——“ui”线程是调用Activity#attach(<params>) 方法的线程。所以我们需要找出什么是“主”线程并比较两者。
看起来下一个提示可以在ActivityThread 类中找到。这个类是一个意大利面条,但我认为有趣的部分是 ActivityThread 对象被实例化的地方。
只有两个地方:public static void main(String[]) 和 public static ActivityThread systemMain()。
这些方法的来源:
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());
Security.addProvider(new AndroidKeyStoreProvider());
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
和:
public static ActivityThread systemMain() {
// The system process on low-memory devices do not get to use hardware
// accelerated drawing, since this can add too much overhead to the
// process.
if (!ActivityManager.isHighEndGfx()) {
HardwareRenderer.disable(true);
} else {
HardwareRenderer.enableForegroundTrimming();
}
ActivityThread thread = new ActivityThread();
thread.attach(true);
return thread;
}
注意这些方法传递给attach(boolean) 的不同值。为了完整起见,我还将发布其来源:
private void attach(boolean system) {
sCurrentActivityThread = this;
mSystemThread = system;
if (!system) {
ViewRootImpl.addFirstDrawHandler(new Runnable() {
@Override
public void run() {
ensureJitEnabled();
}
});
android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
UserHandle.myUserId());
RuntimeInit.setApplicationObject(mAppThread.asBinder());
final IActivityManager mgr = ActivityManagerNative.getDefault();
try {
mgr.attachApplication(mAppThread);
} catch (RemoteException ex) {
// Ignore
}
// Watch for getting close to heap limit.
BinderInternal.addGcWatcher(new Runnable() {
@Override public void run() {
if (!mSomeActivitiesChanged) {
return;
}
Runtime runtime = Runtime.getRuntime();
long dalvikMax = runtime.maxMemory();
long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
if (dalvikUsed > ((3*dalvikMax)/4)) {
if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
+ " total=" + (runtime.totalMemory()/1024)
+ " used=" + (dalvikUsed/1024));
mSomeActivitiesChanged = false;
try {
mgr.releaseSomeActivities(mAppThread);
} catch (RemoteException e) {
}
}
}
});
} else {
// Don't set application object here -- if the system crashes,
// we can't display an alert, we just want to die die die.
android.ddm.DdmHandleAppName.setAppName("system_process",
UserHandle.myUserId());
try {
mInstrumentation = new Instrumentation();
ContextImpl context = ContextImpl.createAppContext(
this, getSystemContext().mPackageInfo);
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();
} catch (Exception e) {
throw new RuntimeException(
"Unable to instantiate Application():" + e.toString(), e);
}
}
// add dropbox logging to libcore
DropBox.setReporter(new DropBoxReporter());
ViewRootImpl.addConfigCallback(new ComponentCallbacks2() {
@Override
public void onConfigurationChanged(Configuration newConfig) {
synchronized (mResourcesManager) {
// We need to apply this change to the resources
// immediately, because upon returning the view
// hierarchy will be informed about it.
if (mResourcesManager.applyConfigurationToResourcesLocked(newConfig, null)) {
// This actually changed the resources! Tell
// everyone about it.
if (mPendingConfiguration == null ||
mPendingConfiguration.isOtherSeqNewer(newConfig)) {
mPendingConfiguration = newConfig;
sendMessage(H.CONFIGURATION_CHANGED, newConfig);
}
}
}
}
@Override
public void onLowMemory() {
}
@Override
public void onTrimMemory(int level) {
}
});
}
为什么有两种初始化ActivityThread(将成为应用程序的“主”线程)的方法?
我认为发生了以下情况:
每当一个新的应用程序启动时,ActivityThread 的 public static void main(String[]) 方法就会被执行。 “主”线程正在那里初始化,并且对Activity 生命周期方法的所有调用都是从那个确切的线程进行的。在Activity#attach() 方法中(其源代码如上所示)系统将“ui”线程初始化为“this”线程,该线程也恰好是“main”线程。因此,对于所有实际情况,“main”线程和“ui”线程都是相同的。
这适用于所有应用程序,只有一个例外。
Android 框架在第一次启动时,也是作为一个应用程序运行的,但是这个应用程序是特殊的(例如:有特权访问)。这种“特殊性”的一部分是它需要一个专门配置的“主”线程。由于它已经通过public static void main(String[]) 方法(就像任何其他应用程序一样),它的“main”和“ui”线程被设置为同一个线程。为了获得具有特殊特性的“主”线程,系统应用程序对public static ActivityThread systemMain()进行静态调用并存储获得的引用。但是它的“ui”线程没有被覆盖,因此“main”和“ui”线程最终是不一样的。