SystemUI简介
SystemUI属于系统级的apk,位置在frameworks\base\packages\SystemUI,主要功能有:
- 状态栏信息显示,比如电池,wifi信号,3G/4G等icon显示
- 通知面板,比如系统消息,第三方应用消息
- 近期任务栏显示面板,比如长按近期任务快捷键,显示近期使用的应用
- 截图服务
- 壁纸服务
- 键盘、toast、画中画等等
SystemUI启动流程分析
#获取包名
在SystemServer.java文件中有以下代码启动SystemUIService
///frameworks/base/services/java/com/android/server/SystemServer.java
// We now tell the activity manager it is okay to run third party
// code. It will call back into us once it has gotten to the state
// where third party code can really run (but before it has actually
// started launching the initial applications), for us to complete our
// initialization.
mActivityManagerService.systemReady(() -> {
//... 其他代码
t.traceBegin("StartSystemUI");
try {
startSystemUi(context, windowManagerF);
} catch (Throwable e) {
reportWtf("starting System UI", e);
}
t.traceEnd();
//...其他代码
}
private static void startSystemUi(Context context, WindowManagerService windowManager) {
PackageManagerInternal pm = LocalServices.getService(PackageManagerInternal.class);
Intent intent = new Intent();
intent.setComponent(pm.getSystemUiServiceComponent());
intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
//Slog.d(TAG, "Starting service: " + intent);
context.startServiceAsUser(intent, UserHandle.SYSTEM);
windowManager.onSystemUiStarted();
}
当ActivityManagerService准备完毕后会调用startSystemUi。
LocalService可以参考 Android系统源码之LocalServices
而PackageManagerInternal的实现在
//frameworks/base/services/core/java/com/android/server/pm/PackageManagerService.java
private class PackageManagerInternalImpl extends PackageManagerInternal {
//...其他代码
@Override
public ComponentName getSystemUiServiceComponent() {
return ComponentName.unflattenFromString(mContext.getResources().getString(
com.android.internal.R.string.config_systemUIServiceComponent));
}
//...其他代码
}
//frameworks/base/core/java/android/content/ComponentName.java
/**
* Recover a ComponentName from a String that was previously created with
* {@link #flattenToString()}. It splits the string at the first '/',
* taking the part before as the package name and the part after as the
* class name. As a special convenience (to use, for example, when
* parsing component names on the command line), if the '/' is immediately
* followed by a '.' then the final class name will be the concatenation
* of the package name with the string following the '/'. Thus
* "com.foo/.Blah" becomes package="com.foo" class="com.foo.Blah".
*
* @param str The String that was returned by flattenToString().
* @return Returns a new ComponentName containing the package and class
* names that were encoded in <var>str</var>
*
* @see #flattenToString()
*/
public static @Nullable ComponentName unflattenFromString(@NonNull String str) {
int sep = str.indexOf('/');
if (sep < 0 || (sep+1) >= str.length()) {
return null;
}
String pkg = str.substring(0, sep);
String cls = str.substring(sep+1);
if (cls.length() > 0 && cls.charAt(0) == '.') {
cls = pkg + cls;
}
return new ComponentName(pkg, cls);
}
unflattenFromString把包名和class路径分开
//config_systemUIServiceComponent在frameworks/base/core/res/res/values/config.xml
<!-- SystemUi service component -->
<string name="config_systemUIServiceComponent" translatable="false"
>com.android.systemui/com.android.systemui.SystemUIService</string>
这里主要是去加载config.xml中SystemUIService包名和具体路径
通过Service去启动具体SystemUI
进入SystemUIService中看看
//frameworks/base/packages/SystemUI/src/com/android/systemui/SystemUIService.java
@Override
public void onCreate() {
super.onCreate();
// Start all of SystemUI
((SystemUIApplication) getApplication()).startServicesIfNeeded();
//...其他代码
}
调用的是SystemUIApplication的startServicesIfNeeded.
//frameworks/base/packages/SystemUI/src/com/android/systemui/SystemUIApplication.java
/**
* Makes sure that all the SystemUI services are running. If they are already running, this is a
* no-op. This is needed to conditinally start all the services, as we only need to have it in
* the main process.
* <p>This method must only be called from the main thread.</p>
*/
public void startServicesIfNeeded() {
String[] names = SystemUIFactory.getInstance().getSystemUIServiceComponents(getResources());
startServicesIfNeeded(/* metricsPrefix= */ "StartServices", names);
}
//frameworks/base/packages/SystemUI/src/com/android/systemui/SystemUIFactory.java
/** Returns the list of system UI components that should be started. */
public String[] getSystemUIServiceComponents(Resources resources) {
return resources.getStringArray(R.array.config_systemUIServiceComponents);
}
//frameworks/base/packages/SystemUI/res/values/config.xml
<!-- SystemUI Services: The classes of the stuff to start. -->
<string-array name="config_systemUIServiceComponents" translatable="false">
<item>com.android.systemui.util.NotificationChannels</item>
<item>com.android.systemui.keyguard.KeyguardViewMediator</item>
<item>com.android.systemui.recents.Recents</item>
<item>com.android.systemui.volume.VolumeUI</item>
<item>com.android.systemui.stackdivider.Divider</item>
<item>com.android.systemui.statusbar.phone.StatusBar</item>
<item>com.android.systemui.usb.StorageNotification</item>
<item>com.android.systemui.power.PowerUI</item>
<item>com.android.systemui.media.RingtonePlayer</item>
<item>com.android.systemui.keyboard.KeyboardUI</item>
<item>com.android.systemui.pip.PipUI</item>
<item>com.android.systemui.shortcut.ShortcutKeyDispatcher</item>
<item>@string/config_systemUIVendorServiceComponent</item>
<item>com.android.systemui.util.leak.GarbageMonitor$Service</item>
<item>com.android.systemui.LatencyTester</item>
<item>com.android.systemui.globalactions.GlobalActionsComponent</item>
<item>com.android.systemui.ScreenDecorations</item>
<item>com.android.systemui.biometrics.AuthController</item>
<item>com.android.systemui.SliceBroadcastRelayHandler</item>
<item>com.android.systemui.SizeCompatModeActivityController</item>
<item>com.android.systemui.statusbar.notification.InstantAppNotifier</item>
<item>com.android.systemui.theme.ThemeOverlayController</item>
<item>com.android.systemui.accessibility.WindowMagnification</item>
<item>com.android.systemui.accessibility.SystemActions</item>
<item>com.android.systemui.toast.ToastUI</item>
</string-array>
可以看到SystemUIFactory根据config_systemUIServiceComponents获取到了SystemUi的服务的class name数组。
接着
//frameworks/base/packages/SystemUI/src/com/android/systemui/SystemUIApplication.java
private void startServicesIfNeeded(String metricsPrefix, String[] services) {
if (mServicesStarted) {
return;
}
mServices = new SystemUI[services.length];
if (!mBootCompleteCache.isBootComplete()) {
// check to see if maybe it was already completed long before we began
// see ActivityManagerService.finishBooting()
if ("1".equals(SystemProperties.get("sys.boot_completed"))) {
mBootCompleteCache.setBootComplete();
if (DEBUG) {
Log.v(TAG, "BOOT_COMPLETED was already sent");
}
}
}
final DumpManager dumpManager = mRootComponent.createDumpManager();
Log.v(TAG, "Starting SystemUI services for user " +
Process.myUserHandle().getIdentifier() + ".");
TimingsTraceLog log = new TimingsTraceLog("SystemUIBootTiming",
Trace.TRACE_TAG_APP);
log.traceBegin(metricsPrefix);
final int N = services.length;
for (int i = 0; i < N; i++) {
String clsName = services[i];
if (DEBUG) Log.d(TAG, "loading: " + clsName);
log.traceBegin(metricsPrefix + clsName);
long ti = System.currentTimeMillis();
try {
SystemUI obj = mComponentHelper.resolveSystemUI(clsName);
if (obj == null) {
Constructor constructor = Class.forName(clsName).getConstructor(Context.class);
obj = (SystemUI) constructor.newInstance(this);
}
mServices[i] = obj;
} catch (ClassNotFoundException
| NoSuchMethodException
| IllegalAccessException
| InstantiationException
| InvocationTargetException ex) {
throw new RuntimeException(ex);
}
if (DEBUG) Log.d(TAG, "running: " + mServices[i]);
mServices[i].start();
log.traceEnd();
// Warn if initialization of component takes too long
ti = System.currentTimeMillis() - ti;
if (ti > 1000) {
Log.w(TAG, "Initialization of " + clsName + " took " + ti + " ms");
}
if (mBootCompleteCache.isBootComplete()) {
mServices[i].onBootCompleted();
}
dumpManager.registerDumpable(mServices[i].getClass().getName(), mServices[i]);
}
mRootComponent.getInitController().executePostInitTasks();
log.traceEnd();
mServicesStarted = true;
}
其中主要的是SystemUI obj = mComponentHelper.resolveSystemUI(clsName);和mServices[i].start();,一个创建对象,一个启动。
先看第一个
//frameworks/base/packages/SystemUI/src/com/android/systemui/dagger/ContextComponentHelper.java
/**
* Interface necessary to make Dagger happy. See {@link ContextComponentResolver}.
*/
public interface ContextComponentHelper {
/** Turns a classname into an instance of the class or returns null. */
Activity resolveActivity(String className);
/** Turns a classname into an instance of the class or returns null. */
RecentsImplementation resolveRecents(String className);
/** Turns a classname into an instance of the class or returns null. */
Service resolveService(String className);
/** Turns a classname into an instance of the class or returns null. */
SystemUI resolveSystemUI(String className);
/** Turns a classname into an instance of the class or returns null. */
BroadcastReceiver resolveBroadcastReceiver(String className);
}
这是个接口,具体的实现在
//frameworks/base/packages/SystemUI/src/com/android/systemui/dagger/ContextComponentResolver.java
/**
* Used during Service and Activity instantiation to make them injectable.
*/
@Singleton
public class ContextComponentResolver implements ContextComponentHelper {
//...其他代码
@Inject
ContextComponentResolver(Map<Class<?>, Provider<Activity>> activityCreators,
Map<Class<?>, Provider<Service>> serviceCreators,
Map<Class<?>, Provider<SystemUI>> systemUICreators,
Map<Class<?>, Provider<RecentsImplementation>> recentsCreators,
Map<Class<?>, Provider<BroadcastReceiver>> broadcastReceiverCreators) {
mActivityCreators = activityCreators;
mServiceCreators = serviceCreators;
mSystemUICreators = systemUICreators;
mRecentsCreators = recentsCreators;
mBroadcastReceiverCreators = broadcastReceiverCreators;
}
/**
* Looks up the SystemUI class name to see if Dagger has an instance of it.
*/
@Override
public SystemUI resolveSystemUI(String className) {
return resolve(className, mSystemUICreators);
}
private <T> T resolve(String className, Map<Class<?>, Provider<T>> creators) {
try {
Class<?> clazz = Class.forName(className);
Provider<T> provider = creators.get(clazz);
return provider == null ? null : provider.get();
} catch (ClassNotFoundException e) {
return null;
}
}
}
这里采用了dagger的方式来提供实例
具体实例如何提供可以看frameworks/base/packages/SystemUI/src/com/android/systemui/dagger/路径下dagger的定义。
接着看mServices[i].start(),
这个就是调用具体各个SystemUI的初始化流程了,就不具体分析了.
总结
- 当ActivityManagerService准备完毕后会调用startSystemUi。
- 然后根据配置文件中的包名路径启动SystemUIService
- 由SystemUIService通过dagger提供实例方式去启动各个SystemUI