gpt4 book ai didi

java - 如何实例化 Android Activity (使用反射)?

转载 作者:IT老高 更新时间:2023-10-28 20:52:18 25 4
gpt4 key购买 nike

今天在一次 Android 采访中被问到这个问题。我回答的是通常的,你知道的,intent + startActivity 等。然后面试官问得更尖锐,

"Yes, but where is it actually instantiated? You don't call new Activity anywhere".

现在回想起来,我真的不知道。他暗示它使用了Java反射,但我没有太多经验,我只用它来访问Android SDK中的一些变量。

谁能解释一下如何使用反射来实例化 Activity ,以及为什么?深入了解面试官在了解这一点时看到了什么值(value),可以获得奖励积分。

最佳答案

当在主屏幕点击应用的启动器图标时,在android系统下会发生以下事件:

  • Homescreen/Launcher app sends an intent to start an activity using startActivity()(startActivity() is binder call to ActivityManager)
  • Activity Manager sends a process fork request using a socket to Zygote.
  • Zygote forks a new VM instance that loads ActivityThread(Activity thread 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.).
  • ActivityThread has real main() for an app.
  • ActivityThread calls the app's onCreate().

因此 ActivityThread 负责实例化 Activity(在 performLaunchActivity 方法中)

解释:

如果你观察堆栈跟踪:

android.app.Instrumentation.newActivity(Instrumentation.java:1021)
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)

实例化新 Activity 的代码:

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
... //More code
Activity activity = null;
try {
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
}
} catch (Exception e) {
if (!mInstrumentation.onException(activity, e)) {
throw new RuntimeException(
"Unable to instantiate activity " + component
+ ": " + e.toString(), e);
}
}
... //More code
return activity;
}

Instrumentation.java(类将在任何应用程序代码之前为您实例化)

public Activity newActivity(ClassLoader cl, String className,
Intent intent)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
return (Activity)cl.loadClass(className).newInstance();
}

关于java - 如何实例化 Android Activity (使用反射)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33617999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com