Search code examples
androiddatetimeraspberry-pi3android-things

When Boot device, if can not connect to the network, how to set current time on android things?


I use Android-Things on Raspberry pi. when booting the device. if connect to the network,

I try TimeManager API.

private void setupTimeZone(String timeZoneName) {
    TimeManager timeManager = TimeManager.getInstance();
    timeManager.setTimeFormat(TimeManager.FORMAT_24);
    timeManager.setTimeZone(timeZoneName);
}

setupTimeZone("Asia/Seoul");

if network is connected to Raspberry pi set time is no problem.

but my problem is only when booting the device, not connect network.

if device not connect network. basically the time is set as Jan 1, 2009 09:00

to change the default date, What files need to be modified?

thanks.


Solution

  • For setting time you can use TimeManager.setTime() method:

    To control device settings using TimeManager, first request the permission com.google.android.things.permission.SET_TIME in your AndroidManifest.xml, then obtain an instance of the class and set the properties appropriate for your app.

     TimeManager timeManager = TimeManager.getInstance();
     // Use 24-hour time
     timeManager.setTimeFormat(TimeManager.FORMAT_24);
    
     // Set time zone to Eastern Standard Time
     timeManager.setTimeZone("America/New_York");
    
     // Set clock time to noon
     Calendar calendar = Calendar.getInstance();
     calendar.set(Calendar.MILLISECOND, 0);
     calendar.set(Calendar.SECOND, 0);
     calendar.set(Calendar.MINUTE, 0);
     calendar.set(Calendar.HOUR_OF_DAY, 12);
     long timeStamp = calendar.getTimeInMillis();
     timeManager.setTime(timeStamp);
    

    but Raspberry Pi 3 has no built-in Real Time Clock (RTC) and there is no possibilities for it to get actual current time without network connection or using external battery-backed RTC module like DS1307 or DS3231 or many others (also take a look at this manual). Often RTC modules use I2C interface, so you should connect RTC module to your board, initially (when your board was connected to network and current time was known) set actual time to it via I2C, and then, on boot get current time from RTC module and set it to Android Things system like in example above. How to control DS3231 RTC via I2C you can find here. Internals of User space driver for that example you can find there.

    Also you can get current time from GPS (e.g. from RMC sentence) and GSM (e.g. AT+CLTS command) modules connected via UART.