GNSS 时间检测

从 Android 12 开始,Android 可以选择使用全球导航卫星系统 (GNSS) 向 time_detector 服务提供 Unix 纪元时间建议。 此功能在 AOSP 中默认处于停用状态。

启用 GNSS 时间检测后,gnss_time_update_service 会被动监听 GNSS 来源的位置信息更新,并向 time_detector 服务提交 GNSS 建议。然后,time_detector 服务会决定是否根据此建议更新系统时钟。

对耗电量的影响

AOSP gnss_time_update_service 会被动监听位置信息更新。这意味着它绝不会主动开启 GPS,也绝不会消耗额外的电量。这还意味着,除非系统中的其他应用或服务主动请求位置信息更新,否则 gnss_time_update_service 不会获得位置信息更新,也不会提供 GNSS 时间建议。

实现

如需启用 GNSS 时间检测,设备制造商必须在系统服务器中明确启用 gnss_time_update_service

必须更新 core/res/res/values/config.xml 文件中的 config_enableGnssTimeUpdateServiceconfig_autoTimeSourcesPriority 值,才能启用此功能。将 config_enableGnssTimeUpdateService 的值设置为 true,并将 gnss 添加到 config_autoTimeSourcesPriority 的项目列表。gnss 在优先级列表中的位置决定了 GNSS 建议相对于来自其他来源的值的优先级。

以下是一个示例 core/res/res/values/config.xml 文件,其中启用了 GNSS 时间检测功能,并且 gnss 在优先级列表中位于第三,在 networktelephony 之后。

<!-- Specifies priority of automatic time sources. Suggestions from higher entries in the list
         take precedence over lower ones.
         See com.android.server.timedetector.TimeDetectorStrategy for available sources. -->
    <string-array name="config_autoTimeSourcesPriority">
        <item>network</item>
        <item>telephony</item>
        <item>gnss</item>
    </string-array>

    <!-- Enables the GnssTimeUpdate service. This is the global switch for enabling Gnss time based
         suggestions to TimeDetector service. See also config_autoTimeSourcesPriority. -->
    <bool name="config_enableGnssTimeUpdateService">true</bool>

调试和测试

如要测试 GNSS 时间检测功能,您可以使用 adb shell cmd location 命令。使用这些命令添加测试位置信息提供程序,通过这些提供程序,您可以指定位置信息和关联的 GNSS 时间。gnss_time_update_service 会监听这些位置信息更新,并定期提供建议。

下面显示了 adb shell cmd location 命令的示例:

# Enable Master Location Switch in the foreground user (usually user 10 on automotive). If you just flashed, this can be done through setup wizard.
adb shell cmd location set-location-enabled true --user 10

# Add GPS test provider (This usually fails the first time. Will throw a SecurityException with "android from <SOME_UID> not allowed to perform MOCK_LOCATION".)
adb shell cmd location providers add-test-provider gps

# Enable mock location permissions for previous UID
adb shell appops set UID_PRINTED_IN_PREVIOUS_ERROR android:mock_location allow

# Add GPS test provider (Should work with no errors.)
adb shell cmd location providers add-test-provider gps

# Enable GPS test provider
adb shell cmd location providers set-test-provider-enabled gps true

# Set location with time (Time can't be lower than the limit set by the lower bound.)
adb shell cmd location providers set-test-provider-location gps --location LATITUDE,LONGITUDE --time TIME