Android学习24 -- Framework层

1 整体框架

有一说一,安卓架构这个概念还是太大了。要写完这东西得出一本书。这些还是简单写一些概要吧。

代码基本是在这个位置:

https://github.com/aosp-mirror/platform_frameworks_base

Android Framework 主要包含以下几个部分:

1. 应用程序层(Application Layer)
应用程序(Apps):就是各种App。

2. 框架层(Framework Layer)

相当于app层的框架,提供很多库和很多管理功能。

3 Native层

这个层级提供了 Android 运行时所需的各种底层库。包括:C 标准库(libc)图形库(Skia)SQLite(数据库)WebKit(Web 内容的渲染引擎)OpenGL ES(图形和3D硬件加速)SSL 和加密(用于处理加密和安全相关的操作)

此外还有很多HAL驱动。

4 Linux 内核(Kernel Layer)
Linux 内核是 Android 系统的基础,负责硬件抽象、内存管理、进程调度、安全性等。Android 对内核进行了优化,以支持移动设备的特定需求,如低功耗和硬件加速等。

2 框架层具体内容

这篇文主要就只是讨论一下安卓的Framework,我对Framework的理解就是上层的类库,类似一个手机版的Windows平台的MFC。主要就是封装了UI的操作,将一些公共的操作抽象成服务提供给终端开发者,简化开发。

2.1 Activity Manager

是负责管理应用组件(如 Activity、Service),负责管理应用程序的生命周期和任务栈。它调度应用程序的启动和停止,以及内存管理和多任务处理。

此时可以查看相关内容dumpsys activity activities

cepheus:/ $ dumpsys activity activities
ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)
Display #0 (activities from top to bottom):
  Stack #26: type=standard mode=fullscreen
  isSleeping=true
  mBounds=Rect(0, 0 - 0, 0)
    mLastPausedActivity: ActivityRecord{49926d9 u0 com.android.settings/.SubSettings t26}
    * Task{7ce3652 #26 visible=true type=standard mode=fullscreen translucent=true A=1000:com.android.settings.root U=0 StackId=26 sz=3}
      mBounds=Rect(0, 0 - 0, 0)
      mMinWidth=-1 mMinHeight=-1
      userId=0 effectiveUid=1000 mCallingUid=u0a85 mUserSetupComplete=true mCallingPackage=com.miui.home mCallingFeatureId=null
      affinity=1000:com.android.settings.root
      intent={act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.android.settings/.MainSettings}
      origActivity=com.android.settings/.MainSettings
      mActivityComponent=com.android.settings/.MiuiSettings
      autoRemoveRecents=false isPersistable=true activityType=1
      rootWasReset=true mNeverRelinquishIdentity=true mReuseTask=false mLockTaskAuth=LOCK_TASK_AUTH_PINNABLE
      Activities=[ActivityRecord{9f25add u0 com.android.settings/.MainSettings t26}, ActivityRecord{443d2a8 u0 com.android.settings/.SubSettings t26}, ActivityRecord{49926d9 u0 com.android.settings/.SubSettings t26}]
      askedCompatMode=false inRecents=true isAvailable=true
      taskId=26 stackId=26
      mHasBeenVisible=true
      mResizeMode=RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION mSupportsPictureInPicture=false isResizeable=true
 supportsSplitScreenWindowingMode=true lastActiveTime=87920285      lastActiveTime=87920285 (inactive for 10985s) pcFlags 0
      * Hist #2: ActivityRecord{49926d9 u0 com.android.settings/.SubSettings t26}
          packageName=com.android.settings processName=com.android.settings
          launchedFromUid=1000 launchedFromPackage=com.android.settings launchedFromFeature=null userId=0
          app=ProcessRecord{fea9731 19556:com.android.settings/1000}
          Intent { act=android.intent.action.MAIN cmp=com.android.settings/.SubSettings (has extras) }
          rootOfTask=false task=Task{7ce3652 #26 visible=true type=standard mode=fullscreen translucent=true A=1000:com.android.settings.root U=0 StackId=26 sz=3}
          taskAffinity=1000:com.android.settings
          mActivityComponent=com.android.settings/.SubSettings
          baseDir=/system/system_ext/priv-app/Settings/Settings.apk
          dataDir=/data/user_de/0/com.android.settings
          stateNotNeeded=false componentSpecified=false mActivityType=standard
          compat={440dpi} labelRes=0x7f1219d2 icon=0x7f08049b theme=0x7f130341
          mLastReportedConfigurations:
            mGlobalConfig={1.0 ?mcc?mnc [zh_CN] ldltr sw392dp w392dp h776dp 440dpi nrml long hdr widecg port finger -keyb/v/h -nav/h winConfig={ mBounds=Rect(0, 0 - 1080, 2340) mAppBounds=Rect(0, 75 - 1080, 2210) mWindowingMode=fullscreen mDisplayWindowingMode=fullscreen mActivityType=undefined mAlwaysOnTop=undefined mRotation=ROTATION_0} s.12 themeChanged=0 themeChangedFlags=0 extraData = Bundle[{}]}
            mOverrideConfig={1.0 ?mcc?mnc [zh_CN] ldltr sw392dp w392dp h776dp 440dpi nrml long hdr widecg port finger -keyb/v/h -nav/h winConfig={ mBounds=Rect(0, 0 - 1080, 2340) mAppBounds=Rect(0, 75 - 1080, 2210) mWindowingMode=fullscreen mDisplayWindowingMode=fullscreen mActivityType=standard mAlwaysOnTop=undefined mRotation=ROTATION_0} s.1 themeChanged=0 themeChangedFlags=0 extraData = Bundle[{}]}
          CurrentConfiguration={1.0 ?mcc?mnc [zh_CN] ldltr sw392dp w392dp h776dp 440dpi nrml long hdr widecg port finger -keyb/v/h -nav/h winConfig={ mBounds=Rect(0, 0 - 1080, 2340) mAppBounds=Rect(0, 75 - 1080, 2210) mWindowingMode=fullscreen mDisplayWindowingMode=fullscreen mActivityType=standard mAlwaysOnTop=undefined mRotation=ROTATION_0} s.1 themeChanged=0 themeChangedFlags=0 extraData = Bundle[{}]}
          taskDescription: label="null" icon=null iconResource=com.android.settings/2131231899 iconFilename=null primaryColor=ffe6e6e6
            backgroundColor=ff000000 statusBarColor=ff000000 navigationBarColor=ffffffff
          launchFailed=false launchCount=0 lastLaunchTime=-16h29m8s940ms
          mHaveState=true mIcicle=Bundle[mParcelledData.dataSize=19904]
          state=STOPPED stopped=true delayedResume=false finishing=false
          keysPaused=false inHistory=true mIsCastMode=false mIsLastFrame=false setToSleep=true idle=true mStartingWindowState=STARTING_WINDOW_NOT_SHOWN
          occludesParent=true noDisplay=false immersive=false launchMode=0
          frozenBeforeDestroy=false forceNewConfig=false
          mActivityType=standard
          windows=[Window{90a7557 mode=0 rootTaskId=26 u0 com.android.settings/com.android.settings.SubSettings}]
          windowType=2 hasVisible=true
          mOccludesParent=true mOrientation=1
          mVisibleRequested=false mVisible=false mClientVisible=false reportedDrawn=false reportedVisible=false
          mAppStopped=true
          mNumInterestingWindows=1 mNumDrawnWindows=1 allDrawn=true lastAllDrawn=true)
          startingData=null firstWindowDrawn=true mIsExiting=false
          mMiuiConfigFlag=1
          nowVisible=false lastVisibleTime=-16h28m45s575ms
          resizeMode=RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION
          mLastReportedMultiWindowMode=false mLastReportedPictureInPictureMode=false
          realComponentName=com.android.settings/.SubSettings

dumpsys activity intents 

127|cepheus:/ $ dumpsys activity intents
ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)
  * com.miui.powerkeeper: 4 items
    #0: PendingIntentRecord{2b3cf70 com.miui.powerkeeper broadcastIntent}
      uid=1000 packageName=com.miui.powerkeeper featureId=null type=broadcastIntent flags=0x0
      requestIntent=act=com.miui.powerkeeper.enter_night pkg=com.miui.powerkeeper
    #1: PendingIntentRecord{5d58040 com.miui.powerkeeper broadcastIntent}
      uid=1000 packageName=com.miui.powerkeeper featureId=null type=broadcastIntent flags=0x0
      requestIntent=act=miui.action.powerkeeper.randomdelay
      sent=true canceled=false
    #2: PendingIntentRecord{a7b4b79 com.miui.powerkeeper startService}
      uid=1000 packageName=com.miui.powerkeeper featureId=null type=startService flags=0x0
      requestIntent=act=miui.intent.action.powerkeeper_alarm cmp=com.miui.powerkeeper/.PowerKeeperBackgroundService
      sent=true canceled=false
    #3: PendingIntentRecord{1430be com.miui.powerkeeper broadcastIntent}
      uid=1000 packageName=com.miui.powerkeeper featureId=null type=broadcastIntent flags=0x0
      requestIntent=act=miui.intent.action.powerkeeper_schedule
      sent=true canceled=false
  * com.android.providers.calendar: 1 items
    #0: PendingIntentRecord{66d51f com.android.providers.calendar broadcastIntent}
      uid=10103 packageName=com.android.providers.calendar featureId=null type=broadcastIntent flags=0x0
      requestCode=100 requestResolvedType=null
      requestIntent=act=com.android.providers.calendar.intent.CalendarProvider2 cmp=com.android.providers.calendar/.CalendarProviderBroadcastReceiver
      sent=true canceled=false
  * com.xiaomi.powerchecker: 1 items
    #0: PendingIntentRecord{5b2606c com.xiaomi.powerchecker broadcastIntent}
      uid=1000 packageName=com.xiaomi.powerchecker featureId=null type=broadcastIntent flags=0x0

AM命令也可以直接管理,

可以实现启动activity

adb shell am start -n com.example.myapp/.MainActivity

启动service

adb shell am startservice -n com.example.myapp/.MyService

发送广播

adb shell am broadcast -a com.example.MY_ACTION --es key "value"

模拟按键

adb shell am keyevent 3  # 模拟按下Home键

具体的用法可以看说明:

cepheus:/ $ am
Activity manager (activity) commands:
  help
      Print this help text.
  start-activity [-D] [-N] [-W] [-P <FILE>] [--start-profiler <FILE>]
          [--sampling INTERVAL] [--streaming] [-R COUNT] [-S]
          [--track-allocation] [--user <USER_ID> | current] <INTENT>
      Start an Activity.  Options are:
      -D: enable debugging
      -N: enable native debugging
      -W: wait for launch to complete
      --start-profiler <FILE>: start profiler and send results to <FILE>
      --sampling INTERVAL: use sample profiling with INTERVAL microseconds
          between samples (use with --start-profiler)
      --streaming: stream the profiling output to the specified file
          (use with --start-profiler)
      -P <FILE>: like above, but profiling stops when app goes idle
      --attach-agent <agent>: attach the given agent before binding
      --attach-agent-bind <agent>: attach the given agent during binding
      -R: repeat the activity launch <COUNT> times.  Prior to each repeat,
          the top activity will be finished.
      -S: force stop the target app before starting the activity
      --track-allocation: enable tracking of object allocations
      --user <USER_ID> | current: Specify which user to run as; if not
          specified then run as the current user.
      --windowingMode <WINDOWING_MODE>: The windowing mode to launch the activity into.
      --activityType <ACTIVITY_TYPE>: The activity type to launch the activity as.
      --display <DISPLAY_ID>: The display to launch the activity into.
  start-service [--user <USER_ID> | current] <INTENT>
      Start a Service.  Options are:
      --user <USER_ID> | current: Specify which user to run as; if not
          specified then run as the current user.
  start-foreground-service [--user <USER_ID> | current] <INTENT>
      Start a foreground Service.  Options are:
      --user <USER_ID> | current: Specify which user to run as; if not
          specified then run as the current user.
  stop-service [--user <USER_ID> | current] <INTENT>
      Stop a Service.  Options are:
      --user <USER_ID> | current: Specify which user to run as; if not
          specified then run as the current user.
  broadcast [--user <USER_ID> | all | current] <INTENT>
      Send a broadcast Intent.  Options are:
      --user <USER_ID> | all | current: Specify which user to send to; if not
          specified then send to all users.
      --receiver-permission <PERMISSION>: Require receiver to hold permission.
      --allow-background-activity-starts: The receiver may start activities
          even if in the background.
  instrument [-r] [-e <NAME> <VALUE>] [-p <FILE>] [-w]

2.2 Window Manager

Window Manager(窗口管理器)是负责管理屏幕上所有窗口(Window)布局、层级、动画和交互的核心系统服务。它直接与 SurfaceFlinger(负责合成和渲染)和 Activity Manager(负责生命周期)协作,确保应用界面正确显示。

管理窗口和屏幕显示,决定如何显示 UI 元素,并为每个应用程序创建一个窗口。它还管理应用程序间的显示和输入事件。

dumpsys window的结果,这里会有大量信息,比如:

窗口信息:列出当前系统中所有的窗口,包含窗口的类型(如应用窗口、系统窗口)、窗口的布局参数(位置、大小)、窗口的焦点状态等。
显示信息:展示屏幕的分辨率、密度、刷新率等显示相关的信息。
输入焦点信息:指示当前获取输入焦点的窗口。
窗口动画信息:显示当前正在运行的窗口动画的相关设置和状态。

127|cepheus:/ $ dumpsys window

WINDOW MANAGER LAST ANR (dumpsys window lastanr)
  <no ANR has occurred since boot>

WINDOW MANAGER POLICY STATE (dumpsys window policy)
    mSafeMode=false mSystemReady=true mSystemBooted=true
    mCameraLensCoverState=CAMERA_LENS_COVER_ABSENT
    mWakeGestureEnabledSetting=false
    mUiMode=UI_MODE_TYPE_NORMALmEnableCarDockHomeCapture=true
    mLidKeyboardAccessibility=0 mLidNavigationAccessibility=0 getLidBehavior=LID_BEHAVIOR_SLEEP
    mLongPressOnBackBehavior=LONG_PRESS_BACK_NOTHING
    mLongPressOnHomeBehavior=LONG_PRESS_HOME_NOTHING
    mDoubleTapOnHomeBehavior=DOUBLE_TAP_HOME_NOTHING
    mShortPressOnPowerBehavior=SHORT_PRESS_POWER_GO_TO_SLEEP
    mLongPressOnPowerBehavior=LONG_PRESS_POWER_GLOBAL_ACTIONS
    mVeryLongPressOnPowerBehavior=VERY_LONG_PRESS_POWER_NOTHING
    mDoublePressOnPowerBehavior=MULTI_PRESS_POWER_NOTHING
    mTriplePressOnPowerBehavior=MULTI_PRESS_POWER_NOTHING
    mShortPressOnSleepBehavior=SHORT_PRESS_SLEEP_GO_TO_SLEEP
    mShortPressOnWindowBehavior=SHORT_PRESS_WINDOW_PICTURE_IN_PICTURE
    mAllowStartActivityForLongPressOnPowerDuringSetup=false
    mHasSoftInput=true mHapticTextHandleEnabled=false
    mDismissImeOnBackKeyPressed=true mIncallPowerBehavior=sleep
    mIncallBackBehavior=<nothing> mEndcallBehavior=sleep
    mDisplayHomeButtonHandlers=    mKeyguardOccluded=false mKeyguardOccludedChanged=false mPendingKeyguardOccluded=false
    mAllowLockscreenWhenOnDisplays=false mLockScreenTimeout=30000 mLockScreenTimerActive=false
    mKeyMapping.size=0
    WakeGestureListener
      mTriggerRequested=false
      mSensor=null
    KeyguardServiceDelegate
      showing=true
      showingAndNotOccluded=true
      inputRestricted=false
      occluded=false
      secure=false
      dreaming=false
      systemIsReady=true
      deviceHasKeyguard=true
      enabled=true
      offReason=OFF_BECAUSE_OF_TIMEOUT

也可以查看合成器dumpsys SurfaceFlinger

cepheus:/ $ dumpsys SurfaceFlinger
Build configuration: [sf PRESENT_TIME_OFFSET=0 FORCE_HWC_FOR_RBG_TO_YUV=1 MAX_VIRT_DISPLAY_DIM=4096 RUNNING_WITHOUT_SYNC_FRAMEWORK=0 NUM_FRAMEBUFFER_SURFACE_BUFFERS=3] [libui] [libgui]

Display identification data:
Display 19260674575326081 (HWC display 0): port=129 pnpId=QCM displayName=""

Wide-Color information:
Device has wide color built-in display: 1
Device uses color management: 1
DisplayColorSetting: Managed
Display 19260674575326081 color modes:
    ColorMode::NATIVE (0)
    ColorMode::SRGB (7)
    ColorMode::DISPLAY_P3 (9)
    Current color mode: ColorMode::SRGB (7)

Sync configuration: [using: EGL_ANDROID_native_fence_sync EGL_KHR_wait_sync]

Scheduler:
+  Idle timer: off
+  Touch timer: off
+  Use content detection: off

Layers rate vote info:
   Rate   | Vote Type       | Weight | Focused | Layer Name
     0.00 | Max             | 1.000  |    1    | NotificationShade#0
     0.00 | Max             | 1.000  |    0    | ColorFade#0
     0.00 | Max             | 1.000  |    0    | com.miui.miwallpaper.superwallpaper.SnowmountainSuperWallpaper#0

ScreenOff: 0d18:36:26.097
60fps: 0d00:12:49.937

           app phase:   1000000 ns               SF phase:   1000000 ns
     early app phase:   1000000 ns         early SF phase:   1000000 ns
  GL early app phase:   1000000 ns      GL early SF phase:   1000000 ns
next VSYNC threshold: 9223372036854775807 ns
      present offset:         0 ns           VSYNC period:  16666666 ns

还有一个就是wm命令

比如查看当前分辨率

cepheus:/ $ wm size
Physical size: 1080x2340

具体用法可以查看命令

cepheus:/ $ wm
Window manager (window) commands:
  help
      Print this help text.
  size [reset|WxH|WdpxHdp] [-d DISPLAY_ID]
    Return or override display size.
    width and height in pixels unless suffixed with 'dp'.
  density [reset|DENSITY] [-d DISPLAY_ID]
    Return or override display density.
  folded-area [reset|LEFT,TOP,RIGHT,BOTTOM]
    Return or override folded area.
  scaling [off|auto] [-d DISPLAY_ID]
    Set display scaling mode.
  dismiss-keyguard
    Dismiss the keyguard, prompting user for auth if necessary.
  set-user-rotation [free|lock] [-d DISPLAY_ID] [rotation]
    Set user rotation mode and user rotation.
  dump-visible-window-views
    Dumps the encoded view hierarchies of visible windows
  set-fix-to-user-rotation [-d DISPLAY_ID] [enabled|disabled]
    Enable or disable rotating display for app requested orientation.

2.3 Content Providers

负责应用程序之间的数据共享。Content Provider 允许一个应用程序访问另一个应用程序的数据库数据。共享数据比如联系人信息之类。

dumpsys activity providers

255|cepheus:/ $ dumpsys activity providers
ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)
  Published single-user content providers (by class):
  * ContentProviderRecord{2178fb0 u0 com.android.providers.telephony/.TelephonyProvider}
    package=com.android.providers.telephony process=com.android.phone
    proc=ProcessRecord{2ad6d80 2998:com.android.phone/1001}
    uid=1001 provider=android.content.ContentProviderProxy@3effe29
    singleton=true
    authority=telephony
  * ContentProviderRecord{955e5ae u0 com.android.providers.telephony/.CarrierProvider}
    package=com.android.providers.telephony process=com.android.phone
    proc=ProcessRecord{2ad6d80 2998:com.android.phone/1001}
    uid=1001 provider=android.content.ContentProviderProxy@821ff4f
    singleton=true
    authority=carrier_information
  * ContentProviderRecord{85df6dc u0 com.android.providers.telephony/.MmsProvider}
    package=com.android.providers.telephony process=com.android.phone
    proc=ProcessRecord{2ad6d80 2998:com.android.phone/1001}
    uid=1001 provider=android.content.ContentProviderProxy@b6153e5
    singleton=true
    authority=mms
  * ContentProviderRecord{81eaeba u0 com.android.providers.settings/.SettingsProvider}
    package=com.android.providers.settings process=system
    proc=ProcessRecord{b0940e3 2000:system/1000}
    uid=1000 provider=android.content.ContentProvider$Transport@c14b0bb
    singleton=true
    authority=settings
    isSyncable=false multiprocess=false initOrder=100
    Connections:
      -> 2741:com.android.systemui/1000 s1/1 u0/0 +1d3h59m22s881ms
      -> 2827:com.miui.miwallpaper:snowmountainSuperWallpaper/u0a139 s1/1 u0/0 +1d3h59m22s780ms
      -> 3046:com.miui.home/u0a85 s1/1 u0/0 +1d3h59m22s211ms
      -> 2998:com.android.phone/1001 s1/1 u0/0 +1d3h59m22s190ms
      -> 2930:org.codeaurora.ims/u0a199 s1/1 u0/0 +1d3h59m20s612ms
      -> 2714:com.miui.miwallpaper/u0a139 s1/1 u0/0 +1d3h59m19s623ms
      -> 3610:com.miui.aod/1000 s1/1 u0/0 +1d3h59m19s599ms
      -> 3576:com.google.android.gms.persistent/u0a188 s1/1 u0/0 +1d3h59m19s452ms
      -> 3957:com.miui.daemon/1000 s1/1 u0/0 +1d3h59m17s998ms
      -> 3924:com.miui.contentcatcher/1000 s1/1 u0/0 +1d3h59m17s656ms
      -> 4158:com.xiaomi.mircs/u0a93 s1/1 u0/0 +1d3h59m17s449ms
      -> 4313:com.android.providers.media.module/u0a220 s1/1 u0/0 +1d3h59m17s254ms
      -> 4295:com.miui.face/1000 s1/1 u0/0 +1d3h59m17s172ms
      -> 4367:com.miui.notification:remote/1000 s1/1 u0/0 +1d3h59m17s169ms

操作命令是content

cepheus:/ $ content
usage: adb shell content [subcommand] [options]

usage: adb shell content insert --uri <URI> [--user <USER_ID>] --bind <BINDING> [--bind <BINDING>...] [--extra <BINDING>...]
  <URI> a content provider URI.
  <BINDING> binds a typed value to a column and is formatted:
  <COLUMN_NAME>:<TYPE>:<COLUMN_VALUE> where:
  <TYPE> specifies data type such as:
  b - boolean, s - string, i - integer, l - long, f - float, d - double, n - null
  Note: Omit the value for passing an empty string, e.g column:s:
  Example:
  # Add "new_setting" secure setting with value "new_value".
  adb shell content insert --uri content://settings/secure --bind name:s:new_setting --bind value:s:new_value

usage: adb shell content update --uri <URI> [--user <USER_ID>] [--where <WHERE>] [--extra <BINDING>...]
  <WHERE> is a SQL style where clause in quotes (You have to escape single quotes - see example below).
  Example:
  # Change "new_setting" secure setting to "newer_value".
  adb shell content update --uri content://settings/secure --bind value:s:newer_value --where "name='new_setting'"

usage: adb shell content delete --uri <URI> [--user <USER_ID>] --bind <BINDING> [--bind <BINDING>...] [--where <WHERE>] [--extra <BINDING>...]
  Example:
  # Remove "new_setting" secure setting.
  adb shell content delete --uri content://settings/secure --where "name='new_setting'"

usage: adb shell content query --uri <URI> [--user <USER_ID>] [--projection <PROJECTION>] [--where <WHERE>] [--sort <SORT_ORDER>] [--extra <BINDING>...]
  <PROJECTION> is a list of colon separated column names and is formatted:
  <COLUMN_NAME>[:<COLUMN_NAME>...]
  <SORT_ORDER> is the order in which rows in the result should be sorted.

比如这个命令可以查看所有联系人

adb shell content query --uri content://com.android.contacts/contacts

2.4 Resource Manager

帮助应用程序访问不同的资源(如字符串、图像、布局文件等),同时支持不同的屏幕大小和分辨率等配置。

这里的资源就是res文件夹下面的资源。

可以使用命令查看dumpsys resource,不过我手上这个设备没有root,貌似不能访问。

cepheus:/ $ dumpsys resource
Can't find service: resource

2.5 Notification Manager

允许应用程序创建和管理通知。通过通知管理器,应用程序可以在设备的状态栏显示通知信息。

当应用程序需要发送通知时,会创建一个 Notification 对象,该对象包含了通知的各种属性,如标题、内容、图标、声音等。然后,应用程序通过 NotificationManager 类将 Notification 对象发送给系统。

可以使用dumpsys notification来查看状态。

cepheus:/ $ dumpsys notification
Current Notification Manager state:
  Notification List:
    NotificationRecord(0x04d37e1b: pkg=com.lbe.security.miui user=UserHandle{0} id=201 tag=null importance=5 key=0|com.lbe.security.miui|201|null|10081: Notification(channel=com.lbe.security.miui shortcut=null contentView=null vibrate=null sound= defaults=0x20 flags=0x10 color=0x00000000 vis=PRIVATE))
      uid=10081 userId=0
      opPkg=com.lbe.security.miui
      icon=Icon(typ=RESOURCE pkg=com.lbe.security.miui id=0x7f0700ab)
      flags=0x10
      pri=1
      key=0|com.lbe.security.miui|201|null|10081
      seen=true
      groupKey=0|com.lbe.security.miui|201|null|10081
      fullscreenIntent=null
      contentIntent=PendingIntent{591fc37: PendingIntentRecord{56bd6b0 com.lbe.security.miui startActivity (whitelist: f6356ba:+30s0ms)}}
      deleteIntent=null
      number=0
      groupAlertBehavior=0
      when=1744794326794
      tickerText=null
      contentView=null
      bigContentView=null
      headsUpContentView=null
      color=0x00000000      timeout=unknown
      extras={
          android.title=String
          android.reduced.images=Boolean (true)
          android.text=String
          android.appInfo=ApplicationInfo (ApplicationInfo{38b55a4 com.lbe.security.miui})
          android.showWhen=Boolean (true)
      }
      stats=SingleNotificationStats{posttimeElapsedMs=210726, posttimeToFirstClickMs=-1, posttimeToDismissMs=-1, airtimeCount=2, airtimeMs=6597, currentAirtimeStartElapsedMs=-1, airtimeExpandedMs=5302, posttimeToFirstVisibleExpansionMs=678, currentAirtimeExpandedStartElapsedMs=-1, requestedImportance=4, naturalImportance=5, isNoisy=true}
      mContactAffinity=0.0
      mRecentlyIntrusive=false
      mPackagePriority=0
      mPackageVisibility=-1000
      mSystemImportance=UNSPECIFIED
      mAsstImportance=UNSPECIFIED
      mImportance=HIGH
      mImportanceExplanation=app

模拟发送通知可以用am的命令,比如

am broadcast

2.6 Package Manager

负责应用程序的安装、卸载、查询及管理应用的权限。

主要是命令行下的pm命令。

cepheus:/ $ pm
Package manager (package) commands:
  help
    Print this help text.

  path [--user USER_ID] PACKAGE
    Print the path to the .apk of the given PACKAGE.

  dump PACKAGE
    Print various system state associated with the given PACKAGE.

  has-feature FEATURE_NAME [version]
    Prints true and returns exit status 0 when system has a FEATURE_NAME,
    otherwise prints false and returns exit status 1

  list features
    Prints all features of the system.

  list instrumentation [-f] [TARGET-PACKAGE]
    Prints all test packages; optionally only those targeting TARGET-PACKAGE
    Options:
      -f: dump the name of the .apk file containing the test package

  list libraries
    Prints all system libraries.

  list packages [-f] [-d] [-e] [-s] [-3] [-i] [-l] [-u] [-U]
      [--show-versioncode] [--apex-only] [--uid UID] [--user USER_ID] [FILTER]
    Prints all packages; optionally only those whose name contains
    the text in FILTER.  Options are:
      -f: see their associated file
      -a: all known packages (but excluding APEXes)
      -d: filter to only show disabled packages
      -e: filter to only show enabled packages
      -s: filter to only show system packages
      -3: filter to only show third party packages
      -i: see the installer for the packages
      -l: ignored (used for compatibility with older releases)
      -U: also show the package UID
      -u: also include uninstalled packages
      --show-versioncode: also show the version code
      --apex-only: only show APEX packages
      --uid UID: filter to only show packages with the given UID
      --user USER_ID: only list packages belonging to the given user

  list permission-groups
    Prints all known permission groups.

  list permissions [-g] [-f] [-d] [-u] [GROUP]
    Prints all known permissions; optionally only those in GROUP.  Options are:
      -g: organize by group
      -f: print all information
      -s: short summary
      -d: only list dangerous permissions
      -u: list only the permissions users will see

  list staged-sessions [--only-ready] [--only-sessionid] [--only-parent]
    Prints all staged sessions.
      --only-ready: show only staged sessions that are ready
      --only-sessionid: show only sessionId of each session
      --only-parent: hide all children sessions

  list users
    Prints all users.

  resolve-activity [--brief] [--components] [--query-flags FLAGS]
       [--user USER_ID] INTENT
    Prints the activity that resolves to the given INTENT.

  query-activities [--brief] [--components] [--query-flags FLAGS]
       [--user USER_ID] INTENT
    Prints all activities that can handle the given INTENT.

  query-services [--brief] [--components] [--query-flags FLAGS]
       [--user USER_ID] INTENT
    Prints all services that can handle the given INTENT.

  query-receivers [--brief] [--components] [--query-flags FLAGS]
       [--user USER_ID] INTENT
    Prints all broadcast receivers that can handle the given INTENT.

  install [-rtfdgw] [-i PACKAGE] [--user USER_ID|all|current]
       [-p INHERIT_PACKAGE] [--install-location 0/1/2]
       [--install-reason 0/1/2/3/4] [--originating-uri URI]
       [--referrer URI] [--abi ABI_NAME] [--force-sdk]
       [--preload] [--instant] [--full] [--dont-kill]
       [--enable-rollback]
       [--force-uuid internal|UUID] [--pkg PACKAGE] [-S BYTES]
       [--apex] [--wait TIMEOUT]
       [PATH [SPLIT...]|-]
    Install an application.  Must provide the apk data to install, either as
    file path(s) or '-' to read from stdin.  Options are:
      -R: disallow replacement of existing application
      -t: allow test packages

比如查看所有安装的包,就可以用pm list packages

1|cepheus:/ $ pm list packages
package:com.miui.screenrecorder
package:com.android.cts.priv.ctsshim
package:com.miui.contentextension
package:com.qualcomm.qti.qcolor
package:com.android.internal.display.cutout.emulation.corner
package:com.google.android.ext.services
package:com.qualcomm.qti.improvetouch.service
package:com.android.internal.display.cutout.emulation.double
package:com.android.providers.telephony
package:com.android.dynsystem
package:com.miui.powerkeeper
package:com.xiaomi.miplay_client
package:com.android.theme.icon.pebble
package:com.unionpay.tsmservice.mi
package:com.miui.qr

具体查看包信息,可以用

pm dump com.miui.screenrecorder

2.7 其它

Location Manager

为应用程序提供位置信息,支持 GPS 或基站定位等功能。

这个主要是代码中实现,比如

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

Telephony Manager

处理与电话相关的操作,包括拨打电话、短信收发等。可以

获取设备信息:可以获取手机的设备编号、软件版本、电话类型等信息。例如,通过 getDeviceId() 方法获取设备的唯一标识,通过 getDeviceSoftwareVersion() 方法获取设备的软件版本号。
获取网络信息:能获取手机所处网络的相关信息,如国家 ISO 代码、运营商编号、运营商名称、网络类型等。比如,使用 getNetworkCountryIso() 方法获取网络所在国家的 ISO 代码,通过 getNetworkOperator() 方法获取运营商编号。
获取 SIM 卡信息:可获取 SIM 卡的状态、SIM 卡运营商编号、SIM 卡运营商名称、SIM 序列号等信息。例如,通过 getSimState() 方法获取 SIM 卡的状态,使用 getSimOperator() 方法获取 SIM 卡运营商编号。
监听电话状态:通过注册 PhoneStateListener 来监听电话的各种状态变化,如来电状态、去电状态、通话过程中的状态等。例如,重写 onCallStateChanged() 方法来处理电话呼叫状态的改变。

这里也是只能通过代码操作

TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

Power Manager

管理设备的电源,包括休眠、唤醒以及管理设备的电池消耗。在开发中,现在一个热点就是快充,调试快充要涉及到这个部分。

查询状态,主要是dumpsys power

cepheus:/ $ dumpsys power
POWER MANAGER (dumpsys power)

Power Manager State:
  Settings power_manager_constants:
    no_cached_wake_locks=true
  mDirty=0x0
  mWakefulness=Asleep
  mWakefulnessChanging=false
  mIsPowered=true
  mPlugType=2
  mBatteryLevel=100
  mBatteryLevelWhenDreamStarted=100
  mDockState=0
  mStayOn=false
  mProximityPositive=false
  mBootCompleted=true
  mSystemReady=true
  mHalAutoSuspendModeEnabled=true
  mHalInteractiveModeEnabled=false
  mWakeLockSummary=0x0
  mNotifyLongScheduled=(none)
  mNotifyLongDispatched=-16s134ms
  mNotifyLongNextCheck=(none)
  mUserActivitySummary=0x0
  mRequestWaitForNegativeProximity=false
  mSandmanScheduled=false
  mSandmanSummoned=false
  mBatteryLevelLow=false
  mLightDeviceIdleMode=false
  mDeviceIdleMode=false
  mDeviceIdleWhitelist=[1001, 2000, 9802, 10074, 10079, 10081, 10082, 10085, 10090, 10100, 10101, 10106, 10115, 10117, 10118, 10119, 10122, 10126, 10144, 10148, 10149, 10153, 10154, 10155, 10157, 10188, 10204, 10205, 10233, 10237, 10238, 10239, 10252, 10258]
  mDeviceIdleTempWhitelist=[]
  mLastWakeTime=66448847 (2930631 ms ago)
  mLastSleepTime=66454848 (2924630 ms ago)
  mLastSleepReason=timeout
  mLastUserActivityTime=66448847 (2930631 ms ago)
  mLastUserActivityTimeNoChangeLights=6865054 (62514424 ms ago)

在开发中,也有相关的类组件。

PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

Sensor Manager:管理 Android 设备上的各种传感器,如加速度传感器、陀螺仪、光线传感器等。

可以使用dumpsys sensorservice来查看传感器状态。

cepheus:/ $ dumpsys sensorservice
Captured at: 21:27:06.396
Sensor Device:
Total 44 h/w sensors, 44 running 0 disabled clients:
0x00000003) active-count = 1; sampling_period(ms) = {200.0}, selected = 200.00 ms; batching_period(ms) = {300000.0}, selected = 300000.00 ms
Sensor List:
0x00000001) vl53l3_tof  Non-wakeup    | ST micro        | ver: 256 | type:    xiaomi.sensor.tof(33171040) | perm: n/a | flags: 0x00000000
        continuous | minRate=2.00Hz | maxRate=100.00Hz | FIFO (max,reserved) = (10000, 0) events | non-wakeUp |
0x00000002) ccd_tilt  Wakeup          | qualcomm        | ver: 256 | type: android.sensor.tilt_detector(22) | perm: n/a | flags: 0x00000007
        special-trigger | maxDelay=0us | minDelay=0us | FIFO (max,reserved) = (10000, 0) events | wakeUp |
0x00000003) pedometer  Wakeup         | qualcomm        | ver: 1 | type: android.sensor.step_detector(18) | perm: android.permission.ACTIVITY_RECOGNITION | flags: 0x00000007
        special-trigger | maxDelay=0us | minDelay=0us | FIFO (max,reserved) = (10000, 300) events | wakeUp |
0x00000004) pedometer  Non-wakeup     | qualcomm        | ver: 1 | type: android.sensor.step_detector(18) | perm: android.permission.ACTIVITY_RECOGNITION | flags: 0x00000006
        special-trigger | maxDelay=0us | minDelay=0us | FIFO (max,reserved) = (10000, 300) events | non-wakeUp |
0x00000005) pedometer  Wakeup         | qualcomm        | ver: 1 | type: android.sensor.step_counter(19) | perm: android.permission.ACTIVITY_RECOGNITION | flags: 0x00000003
        on-change | maxDelay=0us | minDelay=0us | FIFO (max,reserved) = (10000, 300) events | wakeUp |
0x00000006) pedometer  Non-wakeup     | qualcomm        | ver: 1 | type: android.sensor.step_counter(19) | perm: android.permission.ACTIVITY_RECOGNITION | flags: 0x00000002
        on-change | maxDelay=0us | minDelay=0us | FIFO (max,reserved) = (10000, 300) events | non-wakeUp |
0x00000007) stationary_detect_wakeup  | qualcomm        | ver: 1 | type: android.sensor.stationary_detect(29) | perm: n/a | flags: 0x00000005
        one-shot | maxDelay=0us | minDelay=-1us | no batching | wakeUp |
0x00000008) stationary_detect         | qualcomm        | ver: 1 | type: android.sensor.stationary_detect(29) | perm: n/a | flags: 0x00000004
        one-shot | maxDelay=0us | minDelay=-1us | no batching | non-wakeUp |
0x00000009) sns_smd  Wakeup           | qualcomm        | ver: 1 | type: android.sensor.significant_motion(17) | perm: n/a | flags: 0x00000005
        one-shot | maxDelay=0us | minDelay=-1us | no batching | wakeUp |
0x0000000a) lsm6ds3c Accelerometer-Uncalibrated Non-wakeup | STMicro         | ver: 140551 | type: android.sensor.accelerometer_uncalibrated(35) | perm: n/a | flags: 0x00000000
        continuous | minRate=5.00Hz | maxRate=415.97Hz | FIFO (max,reserved) = (10000, 3000) events | non-wakeUp |
0x0000000b) rotation vector  Non-wakeup | xiaomi          | ver: 1 | type: android.sensor.rotation_vector(11) | perm: n/a | flags: 0x00000000
        continuous | minRate=1.00Hz | maxRate=200.00Hz | FIFO (max,reserved) = (10000, 0) events | non-wakeUp |
0x0000000c) orientation  Non-wakeup   | xiaomi          | ver: 1 | type: android.sensor.orientation(3) | perm: n/a | flags: 0x00000000
        continuous | minRate=1.00Hz | maxRate=200.00Hz | FIFO (max,reserved) = (10000, 300) events | non-wakeUp |
0x0000000d) NonUi  Wakeup             | XiaoMi          | ver: 1 | type:  xiaomi.sensor.nonui(33171027) | perm: n/a | flags: 0x00000003
        on-change | maxDelay=0us | minDelay=0us | FIFO (max,reserved) = (10000, 0) events | wakeUp |
0x0000000e) NonUi  Non-wakeup         | XiaoMi          | ver: 1 | type:  xiaomi.sensor.nonui(33171027) | perm: n/a | flags: 0x00000002
        on-change | maxDelay=0us | minDelay=0us | FIFO (max,reserved) = (10000, 0) events | non-wakeUp |
0x0000000f) pickup  Wakeup            | XiaoMi          | ver: 1 | type: xiaomi.sensor.pickup(33171036) | perm: n/a | flags: 0x00000003
        on-change | maxDelay=0us | minDelay=0us | FIFO (max,reserved) = (10000, 0) events | wakeUp |
0x00000010) pickup  Non-wakeup        | XiaoMi          | ver: 1 | type: xiaomi.sensor.pickup(33171036) | perm: n/a | flags: 0x00000002
        on-change | maxDelay=0us | minDelay=0us | FIFO (max,reserved) = (10000, 0) events | non-wakeUp |
0x00000011) 3d_signature  Wakeup      | XiaoMi          | ver: 1 | type: xiaomi.sensor.3d_signature(33171032) | perm: n/a | flags: 0x00000003
        on-change | maxDelay=0us | minDelay=0us | FIFO (max,reserved) = (10000, 0) events | wakeUp |
0x00000012) 3d_signature  Non-wakeup  | XiaoMi          | ver: 1 | type: xiaomi.sensor.3d_signature(33171032) | perm: n/a | flags: 0x00000002
        on-change | maxDelay=0us | minDelay=0us | FIFO (max,reserved) = (10000, 0) events | non-wakeUp |
0x00000013) motion_detect_wakeup      | qualcomm        | ver: 1 | type: android.sensor.motion_detect(30) | perm: n/a | flags: 0x00000005
        one-shot | maxDelay=0us | minDelay=-1us | no batching | wakeUp |
0x00000014) motion_detect             | qualcomm        | ver: 1 | type: android.sensor.motion_detect(30) | perm: n/a | flags: 0x00000004
        one-shot | maxDelay=0us | minDelay=-1us | no batching | non-wakeUp |
0x00000015) tcs3701  Non-wakeup       | ams AG          | ver: 256 | type: xiaomi.sensor.ambientlight.factory(33171007) | perm: n/a | flags: 0x00000000
        continuous | minRate=1.00Hz | maxRate=2000.00Hz | FIFO (max,reserved) = (10000, 0) events | non-wakeUp |
0x00000016) ak0991x Magnetometer-Uncalibrated Non-wakeup | akm             | ver: 20037 | type: android.sensor.magnetic_field_uncalibrated(14) | perm: n/a | flags: 0x00000000
        continuous | minRate=1.00Hz | maxRate=100.00Hz | FIFO (max,reserved) = (10000, 600) events | non-wakeUp |

在代码中,主要是通过SensorManager来操作。

sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

View System

提供了所有视图组件(UI 控件)的基础结构,如 TextView、Button、ImageView 等,用户通过这些控件与应用进行交互。

这部分主要是代码中,各种View。比如

// 在 Activity 中查找一个 TextView
TextView textView = findViewById(R.id.my_text_view);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值