一 : 修改Android系统默认时间

源码路径:frameworks/base/services/java/com/android/server/SystemServer.java
主要变量EARLIEST_SUPPORTED_TIME

  1. // The earliest supported time. We pick one day into 1970, to
  2. // give any timezone code room without going into negative time.
  3. private static final long EARLIEST_SUPPORTED_TIME = 1514764800000L;//20180101 00:00:00

%title插图%num

通过SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME)设置系统时间,只需要修改EARLIEST_SUPPORTED_TIME变量的值。

  1. private void run() {
  2. try {
  3. traceBeginAndSlog(“InitBeforeStartServices”);
  4. // If a device’s clock is before 1970 (before 0), a lot of
  5. // APIs crash dealing with negative numbers, notably
  6. // java.io.File#setLastModified, so instead we fake it and
  7. // hope that time from cell towers or NTP fixes it shortly.
  8. if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
  9. Slog.w(TAG, “System clock is before 1970; setting to 1970.”);
  10. SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
  11. }

%title插图%num

设置系统默认时间这段代码请放在startOtherServices()之后,否则无效(不同的平台代码略有差别,可以自己评价该放在什么位置)。

  1. // Start services.
  2. try {
  3. traceBeginAndSlog(“StartServices”);
  4. startBootstrapServices();
  5. startCoreServices();
  6. startOtherServices();
  7. //add by jasun@180730 for default time start
  8. if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
  9. Slog.w(TAG, “System clock is before 2018.; setting to 2018.”);
  10. SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
  11. }
  12. //add by jasun@180730 for default time end
  13. SystemServerInitThreadPool.shutdown();
  14. } catch (Throwable ex) {
  15. Slog.e(“System”, “******************************************”);
  16. Slog.e(“System”, “************ Failure starting system services”, ex);
  17. throw ex;
  18. } finally {
  19. traceEnd();
  20. }

%title插图%num

二 : 时间转换为UNIX时间戳

EARLIEST_SUPPORTED_TIME变量值如何获取?
Linux命令转换时间戳,如下:

  1. $ date +%s –date 19700101 –utc // 1970-01-01 00:00 UTC
  2. 0
  3. $ date +%s –date 20120101 –utc // 2012-01-01 00:00 UTC
  4. 1325376000
  5. $ date +%s –date 20160101 –utc // 2016-01-01 00:00 UTC
  6. 1451606400

%title插图%num

反之,也可以把某个UNIX时间戳转换为具体日期,如下:

  1. $ date –date=@86400 –utc // Android默认EARLIEST_SUPPORTED_TIME值为86400×1000
  2. 1970 01 02 星期五 00:00:00 UTC
  3. $ date –date=@1451606400 –utc
  4. 2016 01 01 星期五 00:00:00 UTC
  5. $ date –date=@1451606400
  6. 2016 01 01 星期五 08:00:00 CST

%title插图%num