SystemUI 開發總結

SystemUI 開發總結

| 目錄-
SystemUI 有哪內容

初次開發 SystemUI 有哪些彎路?

SystemUI 創建流程?

應用通知視圖是如何跨進程顯示的?

應用窗口的 flag 是如何影響狀態欄的?

後續:SystemUI 能否脫離對系統源碼依賴?

SystemUI 有哪內容

從表面上看, 我們看到的狀態欄、通知欄、下拉菜單、導航欄、鎖屏、最近任務、低電提示等系統頁面都是 SystemUI 的。SystemUI,在源碼目錄中位於: framework/base/packages 目錄下, 可見 SystemUI 和 framework 是關聯的, SystemUI 依賴了很多內部 API , 系統資源, SystemUI 編譯是要依賴系統源碼的。

SystemUI 也是一個應用,不過這個應用特殊之處在於他沒有啓動圖標、也沒有入口 Activity 。他的入口程序是一個服務:SystemUIService。 這個服務會被系統服務拉起來, 這個服務起來, SystemUI 應用進程就創建起來了,具體啓動過程後面會分析。除了 SystemUIService , SystemUI 還有很多服務, 例如: 負責鎖屏的KeyguardService、負責最近任務的 RecentsSystemUserService、負責壁紙的 ImageWallpaper 、負責截屏的TakeScreenshotService 等。

系統移植 、UI 改造

如果要做系統移植, SystemUI 改造這塊的資料還是挺少,大部分情況下都是啃源碼,連蒙帶猜的修改,然後再編譯出來驗證。通常我們會從佈局着手看看哪個佈局長得像就着手去改,不過這塊完全是可以沉澱一下經驗出來讓後人去節省時間的。這裏我也不再贅述了, 有人已經梳理過了, 我借花獻佛吧:https://blog.csdn.net/azhengye/article/details/50419409

架構關係

在系統服務中,有一個服務是專門爲 SystemUI 的狀態欄服務的, 這個服務就是 StatusbarManagerService (簡稱:SMS),和這個服務關係比較密切的服務是 WindowManagerService(簡稱:WMS), SMS 主要管控的是狀態欄、導航欄, 例如:我們可以設置全屏、沉浸式狀態欄都是 SMS 在起作用。

初次開發 SystemUI 有哪些彎路 (環境上的坑)

失敗方案1

IDE獨立編譯 SystemUI , 把 SystemUI 所依賴的系統 jar 都拷貝帶 IDE 下,使用 provided 方式依賴。 在 6.0 以下版本還勉強可行 , 8.0 以後就基本不可能了, 8.0 以後 SystemUI 合入了鎖屏模塊,依賴了太多的系統資源, 編譯不過是一個問題, 就算編譯過了, 所依賴的系統資源 ID 也會不一致。 經過 1~2 兩天的嘗試, 這個方案失敗了。

失敗方案2

使用 Google 源碼編譯, 然後在源碼中修改 SystemUI , 將編譯的 SystemUI 安裝到 MTK 系統的版子上。 發現安裝到 MTK 的板子以後跑不起來, 原因是某些服務啓動不了, 同時也存在資源 ID 不一致的問題。 經過 2~3 天的這條這個方案失敗了。

最終方案


最終不得不麻煩系統同學, 幫忙提供源碼: 在 MTK 源碼中編譯。

爲了提高效率, 使用一臺昨晚編譯機, 另一臺作爲編輯機, 通過 ssh 搭建通道配合完成開發、編譯、安裝三個流程。

SystemUI 是如何啓動的?

前面介紹過 SystemUIService 是 SystemUI 的入庫程序。 SystemUIService 是在服務進程中啓動的,我們來看下源碼:

SystemServer.java 中 SystemServer 是 zygote 進程起來的啓動的第一個服務, 然後在這個服務的 run 方法方法中會一次啓動 Android 系統服務。

private void run() {
    
         // ... 省略一堆代碼
         startBootstrapServices();
         startCoreServices();
         startOtherServices();
         // ... 省略一堆代碼
    
    }
 其中 AMS 是在 startOtherServices() 這個方法中啓動的:
private void startOtherServices() {
    
         // ... 省略一堆代碼
         mActivityManagerService = mSystemServiceManager.startService(
         ActivityManagerService.Lifecycle.class).getService();
         // ... 省略一堆代碼
         mActivityManagerService.systemReady(() -> {
             
             // ... 省略一堆代碼
             try {
                startSystemUi(context, windowManagerF);
             } catch (Throwable e) {
                reportWtf("starting System UI", e);
             } 
             // ... 省略一堆代碼
         });
    
    }

在 AMS 啓動啓動完成之後,會回調一個 systemReady() 傳遞進去的方法, 在其中調用 startSystemUi() 方法啓動了 SystemUI :

static final void startSystemUi(Context context, WindowManagerService windowManager) {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.android.systemui",
                    "com.android.systemui.SystemUIService"));
        intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
        //Slog.d(TAG, "Starting service: " + intent);
        context.startServiceAsUser(intent, UserHandle.SYSTEM);
        windowManager.onSystemUiStarted();
    }

SystemUIService 邏輯也是相當簡單, 啓動之後主要調用 SystemUIApplication 的 startServicesIfNeeded()|

@Override
public void onCreate() {
    super.onCreate();
    ((SystemUIApplication) 
   getApplication()).startServicesIfNeeded();

    // For debugging RescueParty
    if (Build.IS_DEBUGGABLE && 
        SystemProperties.getBoolean("debug.crash_sysui", false)) {
        throw new RuntimeException();
     }
 }           

在 SystemUIApplication 中啓動了 SystemUI 的各個 UI 模塊:

public void startServicesIfNeeded() {
        startServicesIfNeeded(SERVICES);
    }

例如 : SERVICES 包含了狀態欄、電量、畫中畫、 鎖屏等。

通知視圖是如何誇進程顯示的?

跨進程通訊的基礎是 IPC ,通知服務(NotificationManagerService, 簡稱 NMS)也不離開 IPC ,核心架構還是 IPC 架構。

消息通道

  1. 應用做作爲通知的發送端, 需要調用 NMS ,發通知。例如:
String channelId = "channel_1";
          String tag = "ailabs";
          int id = 10086;
          int importance = NotificationManager.IMPORTANCE_LOW;
          NotificationChannel channel = new NotificationChannel(channelId, "123", importance);
          NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
          manager.createNotificationChannel(channel);
          Notification notification = new Notification.Builder(MainActivity.this, channelId)
                  .setCategory(Notification.CATEGORY_MESSAGE)
                  .setSmallIcon(R.mipmap.ic_launcher)
                  .setContentTitle("This is a content title")
                  .setContentText("This is a content text")
                  .setAutoCancel(true)
                  .build();
           // 通知欄要顯示的視圖佈局
          RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.layout_remoteviews);                 
          notification.contentView = remoteViews;
          manager.notify(tag, id , notification);
  1. SystemUI 作爲通知的接收放需要註冊監聽器 INotificationListener 是監聽通通知的一個 AIDL 接口,
    NotificationListenerService 是一個監聽管理服務,他的內部類 NotificationListenerWrapper 實現了
    INotificationListener 接口。 例如:
/** @hide */
        protected class NotificationListenerWrapper extends INotificationListener.Stub {
            @Override
            public void onNotificationPosted(IStatusBarNotificationHolder sbnHolder,
                    NotificationRankingUpdate update) {
                     // 接收通知
                      ....
                     省略了很多代碼
            }
    
            @Override
            public void onNotificationRemoved(IStatusBarNotificationHolder sbnHolder,
                    NotificationRankingUpdate update, NotificationStats stats, int reason) {
                    // 刪除通知
                          ....
                     // 省略了很多代碼
            }

這個通知監聽需要向 NMS 註冊:

@SystemApi
          public void registerAsSystemService(Context context, ComponentName componentName,
                  int currentUser) throws RemoteException {
              if (mWrapper == null) {
                  mWrapper = new NotificationListenerWrapper();
              }
              mSystemContext = context;
              INotificationManager noMan = getNotificationInterface();
              mHandler = new MyHandler(context.getMainLooper());
              mCurrentUser = currentUser;
              noMan.registerListener(mWrapper, componentName, currentUser);
          }
 以上是 Android 爲我們提供的通知接收管理服務類, SystemUI 有個NotificationListenerWithPlugins 類繼承了 NotificationListenerService

類。 並在 SystemUI 進程起來的時候調用 registerAsSystemService() 方法完成了註冊:

NotificationListenerWithPlugins mNotificationListener = new NotificationListenerWithPlugins();
    mNotificationListener.registerAsSystemService();

這樣通道就建立起來了。

消息傳遞過程,大家可以按照這個思路器走讀源碼

<a name="13yage"></a>

RemoteViews

以上只是講解了應用怎麼把一個消息傳遞到 SystemUI , 理解 IPC 通訊的不難理解。 而神奇之處在於顯示的視圖佈局明明是定義在一個應用中,爲何能跨進程顯示到 SystemUI 進程中呢?

發送通知, 傳遞的通知實體是 Notification 的實例, Notification 實現了 Parcelable 接口。 Notification 有個 RemoteViews 的成員變量

RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.layout_remoteviews); notification.contentView = remoteViews;

RemoteViews 也實現了 Parcelable 接口, 主要是封裝了通知欄要展示的視圖信息, 例如, 應用包名、佈局ID。我們都知道實現了 Parcelable 這個接口就可以在 IPC 通道上誇進程傳遞。 RemoteView 支持的佈局類型也是有限的,例如在 8.0 上僅支持如下類型:

  • android.widget.AdapterViewFlipper
    *android.widget.FrameLayout
  • android.widget.GridLayout
  • android.widget.GridView
  • android.widget.LinearLayout
  • android.widget.ListView
  • android.widget.RelativeLayout
  • android.widget.StackView
  • android.widget.ViewFlipper

RemoteView 攜帶了視圖信息, 進程間傳遞的並不是真實的視圖對象, 而主要是佈局的 id ,那麼顯示在通知欄上的視圖對象又是如何創建出來的呢?

通知視圖創建

在通知的接收端創建的,上文說過 NotificationManagerService 內部類 NotificationListenerWrapper 監聽通知消息, 在收到消息之後就在裏面解析消息,並創建視圖了。

protected class NotificationListenerWrapper extends INotificationListener.Stub {
          
          @Override
          public void onNotificationPosted(IStatusBarNotificationHolder sbnHolder,
                  NotificationRankingUpdate update) {
              StatusBarNotification sbn;
              try {
                  sbn = sbnHolder.get();
              } catch (RemoteException e) {
                  Log.w(TAG, "onNotificationPosted: Error receiving StatusBarNotification", e);
                  return;
              }
  
              try {
                  // convert icon metadata to legacy format for older clients
                  createLegacyIconExtras(sbn.getNotification());
                  // 創建視圖
                  maybePopulateRemoteViews(sbn.getNotification());
                  
                  maybePopulatePeople(sbn.getNotification());
              } catch (IllegalArgumentException e) {
                  // warn and drop corrupt notification
                  Log.w(TAG, "onNotificationPosted: can't rebuild notification from " +
                          sbn.getPackageName());
                  sbn = null;
              }
  
              // ... 省略代碼
  
          }
  
          @Override
          public void onNotificationRemoved(IStatusBarNotificationHolder sbnHolder,
                  NotificationRankingUpdate update, NotificationStats stats, int reason) {
              StatusBarNotification sbn;
              //... 省略代碼
  
          }
      }
  在 maybePopulateRemoteViews  這個方法中會去檢查佈局是否要加載, **其實我們比較好奇的是佈局資源在應用進程中,

SystemUI 如何加載遠程進程的佈局資源?**
有兩個關鍵的信息: 包名、佈局ID。知道了包名 SystemUI 進程是有權限創建對應包名的上下文對象的,進而可以拿到對應應用的
資源管理器, 然後就可以加載佈局資源創建對象了。 maybePopulateRemoteViews 方法跟蹤下去, 會走到 RemoteViews 的

private View inflateView(Context context, RemoteViews rv, ViewGroup parent) {
         // RemoteViews may be built by an application installed in another
         // user. So build a context that loads resources from that user but
         // still returns the current users userId so settings like data / time formats
         // are loaded without requiring cross user persmissions.
         final Context contextForResources = getContextForResources(context);
         Context inflationContext = new RemoteViewsContextWrapper(context, contextForResources);
 
         // If mApplyThemeResId is not given, Theme.DeviceDefault will be used.
         if (mApplyThemeResId != 0) {
             inflationContext = new ContextThemeWrapper(inflationContext, mApplyThemeResId);
         }
         LayoutInflater inflater = (LayoutInflater)
                 context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 
         // Clone inflater so we load resources from correct context and
         // we don't add a filter to the static version returned by getSystemService.
         inflater = inflater.cloneInContext(inflationContext);
         inflater.setFilter(this);
         View v = inflater.inflate(rv.getLayoutId(), parent, false);
         v.setTagInternal(R.id.widget_frame, rv.getLayoutId());
         return v;
     }

其中 getContextForResources 中的 context 對象就是通過應用包名創建的上下文對象,創建過程:

private static ApplicationInfo getApplicationInfo(String packageName, int userId) {
          if (packageName == null) {
              return null;
          }
  
          // Get the application for the passed in package and user.
          Application application = ActivityThread.currentApplication();
          if (application == null) {
              throw new IllegalStateException("Cannot create remote views out of an aplication.");
          }
  
          ApplicationInfo applicationInfo = application.getApplicationInfo();
          if (UserHandle.getUserId(applicationInfo.uid) != userId
                  || !applicationInfo.packageName.equals(packageName)) {
              try {
                  Context context = application.getBaseContext().createPackageContextAsUser(
                          packageName, 0, new UserHandle(userId));
                  applicationInfo = context.getApplicationInfo();
              } catch (NameNotFoundException nnfe) {
                  throw new IllegalArgumentException("No such package " + packageName);
              }
          }
  
          return applicationInfo;
    }

只有 SystemUI 才能接收通知嗎?

答案是否定的, 只要有權限註冊通知監聽的應用都可以。 具體權限是: <uses-permission android:name="android.permission.STATUS_BAR_SERVICE"/>
只要應用有這個權限就可以註冊通知監聽了, 這個權限只有系統應用才能申請, 也就是說,只要是系統應用都可以監聽並顯示通知的。 可以寫一個簡單的 demo 測試一下:
一、 申請權限
<uses-permission android:name="android.permission.STATUS_BAR_SERVICE"/>
二、 在佈局中定義一個容器來裝遠程通知視圖

...
     <FrameLayout
         android:layout_width="match_parent"
         android:layout_height="92px"
         android:id="@+id/notification">
 
     </FrameLayout>
     ...
 三、註冊監聽並處理通知顯示邏輯。
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ViewGroup notificationContainer = findViewById(R.id.notification);
        NotificationListenerService listenerService = new NotificationListenerService() {
            @SuppressLint("LongLogTag")
            @Override
            public void onNotificationPosted(StatusBarNotification sbn) {
                super.onNotificationPosted(sbn);
                Log.d("NotificationListenerService", "onNotificationPosted" + sbn);
                if (sbn.getNotification().contentView != null) {
                    View view =  sbn.getNotification().contentView.apply(MainActivity.this, null);
                    notificationContainer.addView(view);
                    view.setVisibility(View.VISIBLE);
                    Log.d("NotificationListenerService", "add contentView");
                }

                if (sbn.getNotification().bigContentView != null) {
                    View view =  sbn.getNotification().bigContentView.apply(MainActivity.this, null);
                    notificationContainer.addView(view);
                    view.setVisibility(View.VISIBLE);
                    Log.d("NotificationListenerService", "add bigContentView");
                }

                if (sbn.getNotification().headsUpContentView != null) {
                    sbn.getNotification().headsUpContentView.apply(MainActivity.this, null);
                    Log.d("NotificationListenerService", "add headsUpContentView");
                }

            }
            @SuppressLint("LongLogTag")
            @Override
            public void onNotificationRemoved(StatusBarNotification sbn) {
                super.onNotificationRemoved(sbn);
                Log.d("NotificationListenerService", "onNotificationRemoved" + sbn);
            }

            @SuppressLint("LongLogTag")
            @Override
            public void onListenerConnected() {
                super.onListenerConnected();
                Log.d("NotificationListenerService", "onNotificationRemoved");
            }

            @Override
            public void onListenerDisconnected() {
                super.onListenerDisconnected();
            }
        };
    // 調用註冊方法 registerAsSystemService 不是公開的 API 反射
try {
            Method method =
                    NotificationListenerService.class.getMethod("registerAsSystemService", Context.class, ComponentName.class, int.class);

            method.setAccessible(true);
            method.invoke(listenerService, this,
                    new ComponentName(getPackageName(), getClass().getCanonicalName()),
                    -1);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

運行起來後,註冊成功, 然後任意應用發通知, 這裏就能顯示出來了。

應用窗口的 flag 是如何狀態欄?


在系統服務中,有一個服務是專門爲 SystemUI 的狀態欄服務的, 這個服務就是 StatusbarManagerService (簡稱:SMS),和這個服務關係比較密切的服務是 WindowManagerService(簡稱:WMS), SMS 主要管控的是狀態欄、導航欄, 例如:我們可以設置全屏、沉浸式狀態欄都是 SMS 在起作用。 我們看一下 window flag 是如何一步一步的影響系統狀態欄的。

通常我們這樣添加窗口屬性,例如設置 flag 讓 SystemUI 狀態欄支持繪製背景:

Window window = activity.getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

我們都知道 Android 系統爲我們提供的 window 實現類是 PhoneWindow (不清楚的可以參考文章:https://www.jianshu.com/p/b4c23dee9206), flag 其實被僅僅是 WindowManager.LayoutParams 的一個標記而已。

public void setFlags(int flags, int mask) {
        final WindowManager.LayoutParams attrs = getAttributes();
        attrs.flags = (attrs.flags&~mask) | (flags&mask);
        mForcedWindowFlags |= mask;
        dispatchWindowAttributesChanged(attrs);
    }

所有窗口的 View 和 LayoutParams 最終會被添加到 WindowManagerService 中,WindowManagerService 會記錄着窗口信息,包括 flag 屬性 。 (View、Window 和 ViewRootImpl 的關係:參考:https://www.jianshu.com/p/47421ec56795
每次窗口布局、焦點發生變化的時候,都會去重新計算當前窗口的屬性, 包括 flag。

public int addWindow(Session session, IWindow client, int seq,
            WindowManager.LayoutParams attrs, int viewVisibility, int displayId,
            Rect outContentInsets, Rect outStableInsets, Rect outOutsets,
            InputChannel outInputChannel) {
            //...省略一堆代碼
            // 計算屬性
            mPolicy.adjustWindowParamsLw(win.mAttrs);
            //...省略一堆代碼
            updateFocusedWindowLocked(UPDATE_FOCUS_WILL_ASSIGN_LAYERS,
                                    false /*updateInputWindows*/);
        }

mPolicy 是 PhoneWindowManager 的一個實例, adjustWindowParamsLw 主要是根據窗口的屬性來決定接下來要展示什麼樣的
SystemUI。例如:

@Override
      public void adjustWindowParamsLw(WindowManager.LayoutParams attrs) {
          // 省略一堆代碼
          if ((attrs.flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0
                  || forceWindowDrawsStatusBarBackground
                          && attrs.height == MATCH_PARENT && attrs.width == MATCH_PARENT) {
              attrs.subtreeSystemUiVisibility |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
          }
      }

接下來, 會調用 PhoneWindowManager 的 focusChangedLw(), 在這裏調用了更新 SystemUI 樣式的方法 updateSystemUiVisibilityLw。

@Override
      public int focusChangedLw(WindowState lastFocus, WindowState newFocus) {
          mFocusedWindow = newFocus;
          if ((updateSystemUiVisibilityLw()&SYSTEM_UI_CHANGING_LAYOUT) != 0) {
              // If the navigation bar has been hidden or shown, we need to do another
              // layout pass to update that window.
              return FINISH_LAYOUT_REDO_LAYOUT;
          }
          return 0;
      }
private int updateSystemUiVisibilityLw() {
          
          mHandler.post(new Runnable() {
                  @Override
                  public void run() {
                      StatusBarManagerInternal statusbar = getStatusBarManagerInternal();
                      if (statusbar != null) {
                          statusbar.setSystemUiVisibility(visibility, fullscreenVisibility,
                                  dockedVisibility, 0xffffffff, fullscreenStackBounds,
                                  dockedStackBounds, win.toString());
                          statusbar.topAppWindowChanged(needsMenu);
                      }
                  }
              });
          return diff;
      }

statusbar 就是 StatusbarManagerService 的一個實例。 在 SystemUI 的啓動過程中, SystemUI 會向 StatusbarManagerService
服務註冊一個回調, 專門用來接收 StatusbarManagerService 的調用, 這個回調器就是 CommandQueue。

public void setSystemUiVisibility(int vis, int fullscreenStackVis, int dockedStackVis,
              int mask, Rect fullscreenStackBounds, Rect dockedStackBounds) {
          synchronized (mLock) {
              // Don't coalesce these, since it might have one time flags set such as
              // STATUS_BAR_UNHIDE which might get lost.
              SomeArgs args = SomeArgs.obtain();
              args.argi1 = vis;
              args.argi2 = fullscreenStackVis;
              args.argi3 = dockedStackVis;
              args.argi4 = mask;
              args.arg1 = fullscreenStackBounds;
              args.arg2 = dockedStackBounds;
              mHandler.obtainMessage(MSG_SET_SYSTEMUI_VISIBILITY, args).sendToTarget();
          }
      }

CommandQueue 收到調用之後就會將消息發送到 SystemUI 的視圖, 視圖再根據收到的 vis 屬性改變樣式。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章