Search code examples
javaandroidadb

Android set system time not persistent after rebooting


I have a problem setting the system time with an adb command. I have realized that the following function (that executes a "toybox date" command) works well in Android 8.1 and 9, but on Android 7.1.2 after rebooting the device, the device shows the time before the execution of the command (the previous time).

So, summarizing, the steps to reproduce the problem are:

  1. Execute the following snippet (the time passed as parameter must be different to current system time)
  2. Reboot the device
  3. Check the device time. The device shows the time before changing the system time

Android OS:

  • With Android 7.1.2: the system time set not persists after reboot (I have tested with 2 different devices)
  • With Android 8.1 and 9: the system time set persists after reboot

The function to change system time:

public static void changeSystemTime(String year, String month, String day, String hour, String minute, String second) {
    Process process = null;
    try {
        String command = "su 0 toybox date " + month + day + hour + minute + year + '.' + second + '\n';
        process = Runtime.getRuntime().exec(command);
        process.waitFor();
    } catch (Exception e) {
        MyLogger.add(Level.SEVERE, "UsefulTools, changeSystemTime: " + MyLogger.generateLogMessage(e));
    } finally {
        if (process != null)
            process.destroy();
    }
}

On my AndroidManifest.xml I have the permissions to set the system time:

<uses-permission android:name="android.permission.SET_TIME"
    android:protectionLevel="signature|system"
    tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.SET_TIME_ZONE"
    android:protectionLevel="signature|system"
    tools:ignore="ProtectedPermissions" />

I have tried to change the system time with the date command instead but happens the same. Why this is happening? Any ideas to make the system set persistent?


Solution

  • I have found the solution. I will explain here if it could help somebody in the future.

    I have tested these commands on Android 7.1.2 and work well, but on Android 8.1 does not work (but toybox date work well as I said).

    There are system time and hardware time, and toybox date only changes the system time on Android 7.1.2. It is necessary to run these commands after the toybox date command to save the time to the hardware time too. Run on ADB shell:

    1. hwclock -uw
    2. sync

    And after rebooting the time persists.