Search code examples
androidwidgetandroid-jobscheduler

Android O: can we make a clock widget?


There is a clock widget in our app. The widget needs to be updated every minute to display the time right.

In Android O, it is advised to use JobScheduler for background updates. Unfortunately, there are limitations.

  1. The periodic updates of JobService can not be called in less than 15 minutes intervals.
  2. The moment JobService.onStartJob() is unpredictable. We may miss the exact moment to update the minute digit (59th second).

Prior O we used to run a background service with Handler.postDelayed() to update the time in the widget. In O the background service can be terminated by the system.

How would you recommend to implement a clock widget in Android O?

Is this even possible now?

enter image description here


Solution

  • Use "TextClock" widget control, it is supported by RemoteView functionality and it updates every minute by it self, no need to use those fancy JobScheduler jobs.

    Something like this will do the trick:

    <LinearLayout
        android:id="@+id/root"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    
        <TextClock
            android:id="@+id/dateText"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:format12Hour="@string/date_text_format_12h"
            android:format24Hour="@string/date_text_format_24h"
            android:gravity="bottom|center_horizontal"
            android:textColor="@android:color/black"
            android:textSize="@dimen/date_text_size_default"/>
    
        <TextClock
            android:id="@+id/timeText"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:format12Hour="@string/time_text_format_12h"
            android:format24Hour="@string/time_text_format_24h"
            android:gravity="top|center_horizontal"
            android:textColor="@android:color/black"
            android:textSize="@dimen/time_text_size_default"
            android:textStyle="bold"/>
    
    </LinearLayout>