Skip to content

Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.

addons: Sleep Timer, standby after 15 to 120 minutes with a one-minute warning

Luiz Fernando0dcd814a7d37
diff --git a/addons/README.md b/addons/README.md
index 7136a318a..a7af5e3ff 100644
--- a/addons/README.md
+++ b/addons/README.md
@@ -15,6 +15,7 @@ the core bigger or change how it behaves. You install an add-on only if you want
| [Photo Prints](photo-prints/) | Your own photos as a screensaver: dated prints dealt in on a time-of-day sky, and a card that starts the slideshow | [@shivamsingh262](https://github.com/shivamsingh262) | Sony BRAVIA KD-65X82L (Google TV 12) | None |
| [Photo screensaver](photo-screensaver/) | Your own pictures and MP4 clips as the TV's screensaver and as a card, slowly zooming and crossfading (20 s each by default); optional time, photo dates, prints on a sky and weather | [JorickGU](https://github.com/JorickGU) | TCL 43P69K (Google TV 12) | `INTERNET` and coarse location, only with the weather option on |
| [Prayer Times](prayer-times/) | Today's prayer times for one city from Aladhan (no key), the next prayer with a countdown, Gregorian and Hijri dates | [@majnioui](https://github.com/majnioui) | Xiaomi TV (MiTV-MOOR2), Google TV 11 | `INTERNET` |
+| [Sleep Timer](sleep-timer/) | A sleep timer: 15 to 120 minutes, a one-minute countdown over what is playing with "15 more minutes", then standby; over HDMI-CEC the TV turns off with the box | [@luyzfernando08](https://github.com/luyzfernando08) | Xiaomi Mi Box S (Android TV 9) | accessibility (lock-screen action only), display over other apps, exact alarms |
A widget, an info tile, a storage or smart-home card: if it can live as its own small app, it can live
here. See the rules below.
diff --git a/addons/sleep-timer/.gitignore b/addons/sleep-timer/.gitignore
new file mode 100644
index 000000000..875cd7fd6
--- /dev/null
+++ b/addons/sleep-timer/.gitignore
@@ -0,0 +1,3 @@
+app/build/
+.gradle/
+build/
diff --git a/addons/sleep-timer/README.md b/addons/sleep-timer/README.md
new file mode 100644
index 000000000..819deb1db
--- /dev/null
+++ b/addons/sleep-timer/README.md
@@ -0,0 +1,58 @@
+# Sleep Timer
+
+A sleep timer for Android TV: pick 15, 30, 60, 90 or 120 minutes, and the TV goes to standby when it runs
+out. One minute before, a small countdown shows over whatever is playing with **15 more minutes** and
+**Turn off now**; if nobody answers, the TV goes to standby. Back leaves the warning but not the timer.
+
+Package `io.github.luyzfernando08.sleeptimer`. You see it as **Sleep Timer** (Portuguese: **Desligar**). On
+cleanyourtv's Home it is also a module card, **Sleep Timer**, which opens the picker; the picker shows when the
+TV will turn off and can cancel the timer.
+
+## How it turns the TV off
+
+An ordinary app cannot put Android to sleep: there is no permission for it. A device admin's `lockNow()` is
+ignored on boxes without the device-admin feature (a Xiaomi Mi Box S is one). What works is the accessibility
+"lock screen" global action, which since Android 9 sends the device to sleep, so the app has an accessibility
+service that does that one thing and nothing else.
+
+On a box behind HDMI, sleeping also turns the TV off when the box has HDMI-CEC on: Android sends
+`<Inactive Source>`, waits for pending CEC actions to clear and then sends `<Standby>` to the TV, exactly as
+for the remote's power key. One catch, seen on the Mi Box S: for a few seconds after waking, the box runs a
+"one touch play" action that holds the `<Standby>` back, so only the box sleeps. A timer of 15 minutes or more
+never hits that.
+
+## Install
+
+JDK 17 and Android SDK 34, as for the launcher, and the `tools/venv` from the main README. The `gradlew`
+scripts reuse the launcher's pinned Gradle wrapper with this folder as the project. Android 9 or later.
+
+```sh
+TV_HOST=192.168.1.50 addons/sleep-timer/build-and-install.sh
+TV_HOST=192.168.1.50 addons/sleep-timer/build-and-install.sh --uninstall
+```
+
+```powershell
+powershell -ExecutionPolicy Bypass -File addons\sleep-timer\build-and-install.ps1 -TvHost 192.168.1.50 [-Uninstall]
+```
+
+Then press Home and answer **Show card** if you want the card; Keep hidden leaves an ordinary app tile. To try
+it without waiting, the first lines of `build-and-install.sh` have an adb command for a 70-second timer.
+
+## Permissions
+
+- **Accessibility service** (`SleepService`), switched on by the install script: only for the lock-screen
+ global action. It asks for no events (`typeAnnouncement` only, which it ignores), cannot retrieve window
+ content and reads no keys. The uninstall takes it off the enabled list and leaves any other services alone.
+- **Display over other apps** (`SYSTEM_ALERT_WINDOW`), granted with `appops`: Android 10 and later only let an
+ app open its warning from the background when it holds this. The app draws no overlay window.
+- **Exact alarms** (`SCHEDULE_EXACT_ALARM`), granted with `appops` where it exists (Android 12+), so the
+ timer fires on the minute; without it the alarm may come a few minutes late.
+- No network, no storage permission, no background service: between setting the timer and its end there are
+ two alarms and nothing running.
+- **`AlarmReceiver`** is exported only to callers holding `WRITE_SECURE_SETTINGS`, which the adb shell has and
+ ordinary apps cannot get, for the test action above. **`TimerActivity`** (exported) is the tile and the card.
+
+## Tested on
+
+Xiaomi Mi Box S (MIBOX4, Android TV 9) with the reference launcher 2.6: the card, the picker, the warning at
+one minute, standby on the second, and the TV turned off with it over HDMI-CEC.
diff --git a/addons/sleep-timer/app/build.gradle b/addons/sleep-timer/app/build.gradle
new file mode 100644
index 000000000..5637e6336
--- /dev/null
+++ b/addons/sleep-timer/app/build.gradle
@@ -0,0 +1,30 @@
+plugins {
+ id 'com.android.application'
+}
+
+android {
+ namespace 'io.github.luyzfernando08.sleeptimer'
+ compileSdk 34
+
+ defaultConfig {
+ applicationId 'io.github.luyzfernando08.sleeptimer'
+ minSdk 28 // GLOBAL_ACTION_LOCK_SCREEN, which puts the TV to sleep, is Android 9
+ targetSdk 34
+ versionCode 1
+ versionName '1.0'
+ }
+
+ buildTypes {
+ release {
+ minifyEnabled true
+ proguardFiles getDefaultProguardFile('proguard-android-optimize.txt')
+ // Sideloaded over ADB, never published.
+ signingConfig signingConfigs.debug
+ }
+ }
+
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_17
+ targetCompatibility JavaVersion.VERSION_17
+ }
+}
diff --git a/addons/sleep-timer/app/src/main/AndroidManifest.xml b/addons/sleep-timer/app/src/main/AndroidManifest.xml
new file mode 100644
index 000000000..a15fefd54
--- /dev/null
+++ b/addons/sleep-timer/app/src/main/AndroidManifest.xml
@@ -0,0 +1,62 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+
+ <!-- Android 12+: the timer fires on the minute; without it the alarm may come a few minutes late. -->
+ <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
+ <!-- Android 10 and later only let an app open the warning from the background when it may draw over other
+ apps. the install script grants it; on Android 9 it is not needed. -->
+ <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
+
+ <uses-feature android:name="android.software.leanback" android:required="false" />
+ <uses-feature android:name="android.hardware.touchscreen" android:required="false" />
+
+ <application
+ android:allowBackup="false"
+ android:banner="@drawable/banner"
+ android:icon="@drawable/banner"
+ android:label="@string/app_name">
+
+ <!-- The timer picker: the app's own tile and, on the cleanyourtv launcher, its module card. -->
+ <activity
+ android:name=".TimerActivity"
+ android:exported="true"
+ android:theme="@android:style/Theme.DeviceDefault.NoActionBar">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
+ </intent-filter>
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="com.gathin.tvhome.category.DOCK_CARD" />
+ </intent-filter>
+ <meta-data android:name="com.gathin.tvhome.card" android:resource="@xml/module_card" />
+ </activity>
+
+ <!-- The last minute: a countdown over whatever is playing, with "15 more minutes" and "Now". -->
+ <activity
+ android:name=".WarningActivity"
+ android:exported="false"
+ android:excludeFromRecents="true"
+ android:launchMode="singleInstance"
+ android:theme="@style/Warning" />
+
+ <!-- Exported only to callers holding WRITE_SECURE_SETTINGS (the adb shell), for the TEST action. -->
+ <receiver
+ android:name=".AlarmReceiver"
+ android:exported="true"
+ android:permission="android.permission.WRITE_SECURE_SETTINGS" />
+
+ <!-- Its only job is the "lock screen" global action, which on Android 9 and later puts the TV to sleep: an
+ ordinary app has no other way to. It asks for no events and cannot read the screen. -->
+ <service
+ android:name=".SleepService"
+ android:exported="true"
+ android:label="@string/service_label"
+ android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE">
+ <intent-filter>
+ <action android:name="android.accessibilityservice.AccessibilityService" />
+ </intent-filter>
+ <meta-data android:name="android.accessibilityservice" android:resource="@xml/sleep_service" />
+ </service>
+ </application>
+</manifest>
diff --git a/addons/sleep-timer/app/src/main/java/io/github/luyzfernando08/sleeptimer/AlarmReceiver.java b/addons/sleep-timer/app/src/main/java/io/github/luyzfernando08/sleeptimer/AlarmReceiver.java
new file mode 100644
index 000000000..cbd9e2af0
--- /dev/null
+++ b/addons/sleep-timer/app/src/main/java/io/github/luyzfernando08/sleeptimer/AlarmReceiver.java
@@ -0,0 +1,25 @@
+package io.github.luyzfernando08.sleeptimer;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+
+/** The timer's two alarms: a minute early, the warning; just after the end, sleep if nobody answered. */
+public class AlarmReceiver extends BroadcastReceiver {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ if (Timer.ACTION_TEST.equals(intent.getAction())) {
+ // From adb only (the receiver needs WRITE_SECURE_SETTINGS): a timer of a few seconds, to try it out.
+ Timer.startSeconds(context, intent.getIntExtra("seconds", 70));
+ return;
+ }
+ long end = Timer.end(context);
+ if (end == 0) return; // cancelled, or pushed back since
+ if (Timer.ACTION_WARN.equals(intent.getAction())) {
+ context.startActivity(new Intent(context, WarningActivity.class)
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
+ } else if (Timer.ACTION_SLEEP.equals(intent.getAction()) && System.currentTimeMillis() >= end) {
+ Timer.sleepNow(context);
+ }
+ }
+}
diff --git a/addons/sleep-timer/app/src/main/java/io/github/luyzfernando08/sleeptimer/SleepService.java b/addons/sleep-timer/app/src/main/java/io/github/luyzfernando08/sleeptimer/SleepService.java
new file mode 100644
index 000000000..096e8c8b6
--- /dev/null
+++ b/addons/sleep-timer/app/src/main/java/io/github/luyzfernando08/sleeptimer/SleepService.java
@@ -0,0 +1,41 @@
+package io.github.luyzfernando08.sleeptimer;
+
+import android.accessibilityservice.AccessibilityService;
+import android.view.accessibility.AccessibilityEvent;
+
+/**
+ * Puts the TV to sleep for Timer. The "lock screen" global action (Android 9 and later) sends the device to
+ * sleep, which an ordinary app cannot do otherwise; a device admin's lockNow() is ignored on boxes without the
+ * device-admin feature, the Mi Box S among them. The service asks for no events and reads no windows.
+ */
+public class SleepService extends AccessibilityService {
+ private static SleepService instance;
+
+ static boolean running() {
+ return instance != null;
+ }
+
+ static boolean sleep() {
+ SleepService service = instance;
+ return service != null && service.performGlobalAction(GLOBAL_ACTION_LOCK_SCREEN);
+ }
+
+ @Override
+ protected void onServiceConnected() {
+ instance = this;
+ }
+
+ @Override
+ public void onAccessibilityEvent(AccessibilityEvent event) {
+ }
+
+ @Override
+ public void onInterrupt() {
+ }
+
+ @Override
+ public void onDestroy() {
+ instance = null;
+ super.onDestroy();
+ }
+}
diff --git a/addons/sleep-timer/app/src/main/java/io/github/luyzfernando08/sleeptimer/Timer.java b/addons/sleep-timer/app/src/main/java/io/github/luyzfernando08/sleeptimer/Timer.java
new file mode 100644
index 000000000..e8bc4a829
--- /dev/null
+++ b/addons/sleep-timer/app/src/main/java/io/github/luyzfernando08/sleeptimer/Timer.java
@@ -0,0 +1,77 @@
+package io.github.luyzfernando08.sleeptimer;
+
+import android.app.AlarmManager;
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.os.Build;
+
+/**
+ * The one timer: when it ends, and the two alarms behind it. The warning alarm fires a minute early and opens
+ * WarningActivity; the sleep alarm, a moment after the end, is the backstop that puts the TV to sleep even if
+ * the warning never showed.
+ */
+final class Timer {
+ private Timer() { }
+
+ static final int[] MINUTES = {15, 30, 60, 90, 120};
+ static final long WARN_MS = 60_000;
+ static final String ACTION_WARN = "io.github.luyzfernando08.sleeptimer.WARN";
+ static final String ACTION_SLEEP = "io.github.luyzfernando08.sleeptimer.SLEEP";
+ static final String ACTION_TEST = "io.github.luyzfernando08.sleeptimer.TEST";
+
+ private static SharedPreferences prefs(Context ctx) {
+ return ctx.getSharedPreferences("timer", Context.MODE_PRIVATE);
+ }
+
+ /** When the TV goes to sleep, in wall-clock millis, or 0 when no timer is on. */
+ static long end(Context ctx) {
+ long end = prefs(ctx).getLong("end", 0);
+ return end > System.currentTimeMillis() - 5_000 ? end : 0;
+ }
+
+ static void start(Context ctx, int minutes) {
+ startSeconds(ctx, minutes * 60);
+ }
+
+ static void startSeconds(Context ctx, int seconds) {
+ long end = System.currentTimeMillis() + seconds * 1000L;
+ prefs(ctx).edit().putLong("end", end).apply();
+ schedule(ctx, ACTION_WARN, Math.max(System.currentTimeMillis(), end - WARN_MS));
+ schedule(ctx, ACTION_SLEEP, end + 2_000);
+ }
+
+ static void cancel(Context ctx) {
+ prefs(ctx).edit().remove("end").apply();
+ AlarmManager am = ctx.getSystemService(AlarmManager.class);
+ am.cancel(pending(ctx, ACTION_WARN));
+ am.cancel(pending(ctx, ACTION_SLEEP));
+ }
+
+ /** Ends the timer and puts the TV to sleep. False when the accessibility service is off. */
+ static boolean sleepNow(Context ctx) {
+ cancel(ctx);
+ return SleepService.sleep();
+ }
+
+ static boolean canSleep() {
+ return SleepService.running();
+ }
+
+ private static void schedule(Context ctx, String action, long at) {
+ AlarmManager am = ctx.getSystemService(AlarmManager.class);
+ PendingIntent pi = pending(ctx, action);
+ if (Build.VERSION.SDK_INT >= 31 && !am.canScheduleExactAlarms()) {
+ am.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pi);
+ } else {
+ am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pi);
+ }
+ }
+
+ private static PendingIntent pending(Context ctx, String action) {
+ Intent intent = new Intent(ctx, AlarmReceiver.class).setAction(action);
+ return PendingIntent.getBroadcast(ctx, 0, intent,
+ PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
+ }
+}
diff --git a/addons/sleep-timer/app/src/main/java/io/github/luyzfernando08/sleeptimer/TimerActivity.java b/addons/sleep-timer/app/src/main/java/io/github/luyzfernando08/sleeptimer/TimerActivity.java
new file mode 100644
index 000000000..1201c3370
--- /dev/null
+++ b/addons/sleep-timer/app/src/main/java/io/github/luyzfernando08/sleeptimer/TimerActivity.java
@@ -0,0 +1,78 @@
+package io.github.luyzfernando08.sleeptimer;
+
+import android.app.Activity;
+import android.graphics.Color;
+import android.os.Bundle;
+import android.text.format.DateFormat;
+import android.view.Gravity;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+/** The card: pick when the TV goes to sleep, or cancel the timer. Choosing closes the screen. */
+public class TimerActivity extends Activity {
+ private TextView state, first, cancel;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ LinearLayout root = new LinearLayout(this);
+ root.setOrientation(LinearLayout.VERTICAL);
+ root.setGravity(Gravity.CENTER_HORIZONTAL);
+ root.setBackgroundColor(0xFF0B0D12);
+ int pad = Ui.dp(this, 48);
+ root.setPadding(pad, pad, pad, pad);
+
+ TextView title = Ui.text(this, 34, Color.WHITE);
+ title.setText(R.string.app_name);
+ root.addView(title);
+ TextView hint = Ui.text(this, 16, 0xB3FFFFFF);
+ hint.setText(R.string.hint);
+ hint.setPadding(0, Ui.dp(this, 8), 0, Ui.dp(this, 4));
+ root.addView(hint);
+ state = Ui.text(this, 18, 0xFFB9B2FF);
+ state.setPadding(0, Ui.dp(this, 8), 0, Ui.dp(this, 16));
+ root.addView(state);
+
+ // The lengths side by side, so the whole screen fits a 1080p TV; Cancel underneath.
+ LinearLayout lengths = new LinearLayout(this);
+ lengths.setOrientation(LinearLayout.HORIZONTAL);
+ lengths.setGravity(Gravity.CENTER_HORIZONTAL);
+ root.addView(lengths);
+ for (int minutes : Timer.MINUTES) {
+ TextView row = Ui.row(lengths, 150);
+ if (minutes != Timer.MINUTES[Timer.MINUTES.length - 1]) {
+ ((LinearLayout.LayoutParams) row.getLayoutParams()).setMarginEnd(Ui.dp(this, 12));
+ }
+ row.setGravity(Gravity.CENTER);
+ row.setText(getString(R.string.in_minutes, minutes));
+ row.setOnClickListener(v -> {
+ Timer.start(this, minutes);
+ finish();
+ });
+ if (first == null) first = row;
+ }
+ cancel = Ui.row(root, 798);
+ cancel.setText(R.string.cancel);
+ cancel.setOnClickListener(v -> {
+ Timer.cancel(this);
+ refresh();
+ });
+
+ setContentView(root);
+ }
+
+ /** Also when the screen comes back from the background, so it never shows a timer that has changed. */
+ @Override
+ protected void onResume() {
+ super.onResume();
+ refresh();
+ (Timer.end(this) != 0 ? cancel : first).requestFocus();
+ }
+
+ private void refresh() {
+ long end = Timer.end(this);
+ if (!Timer.canSleep()) state.setText(R.string.no_service);
+ else if (end == 0) state.setText(R.string.state_off);
+ else state.setText(getString(R.string.state_on, DateFormat.getTimeFormat(this).format(end)));
+ }
+}
diff --git a/addons/sleep-timer/app/src/main/java/io/github/luyzfernando08/sleeptimer/Ui.java b/addons/sleep-timer/app/src/main/java/io/github/luyzfernando08/sleeptimer/Ui.java
new file mode 100644
index 000000000..bf1810f10
--- /dev/null
+++ b/addons/sleep-timer/app/src/main/java/io/github/luyzfernando08/sleeptimer/Ui.java
@@ -0,0 +1,51 @@
+package io.github.luyzfernando08.sleeptimer;
+
+import android.content.Context;
+import android.graphics.Color;
+import android.graphics.drawable.GradientDrawable;
+import android.graphics.drawable.StateListDrawable;
+import android.util.TypedValue;
+import android.view.Gravity;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+/** The few views both screens share: rounded rows that light up when focused. */
+final class Ui {
+ private Ui() { }
+
+ static TextView text(Context ctx, int sp, int color) {
+ TextView view = new TextView(ctx);
+ view.setTextColor(color);
+ view.setTextSize(TypedValue.COMPLEX_UNIT_SP, sp);
+ return view;
+ }
+
+ static TextView row(LinearLayout parent, int widthDp) {
+ Context ctx = parent.getContext();
+ TextView row = text(ctx, 20, Color.WHITE);
+ row.setGravity(Gravity.CENTER_VERTICAL);
+ row.setPadding(dp(ctx, 24), dp(ctx, 14), dp(ctx, 24), dp(ctx, 14));
+ row.setFocusable(true);
+ row.setClickable(true);
+ StateListDrawable bg = new StateListDrawable();
+ bg.addState(new int[]{android.R.attr.state_focused}, pill(ctx, 0x40FFFFFF));
+ bg.addState(new int[]{}, pill(ctx, 0x14FFFFFF));
+ row.setBackground(bg);
+ LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(dp(ctx, widthDp),
+ LinearLayout.LayoutParams.WRAP_CONTENT);
+ lp.topMargin = dp(ctx, 10);
+ parent.addView(row, lp);
+ return row;
+ }
+
+ static GradientDrawable pill(Context ctx, int color) {
+ GradientDrawable d = new GradientDrawable();
+ d.setColor(color);
+ d.setCornerRadius(dp(ctx, 28));
+ return d;
+ }
+
+ static int dp(Context ctx, int v) {
+ return Math.round(v * ctx.getResources().getDisplayMetrics().density);
+ }
+}
diff --git a/addons/sleep-timer/app/src/main/java/io/github/luyzfernando08/sleeptimer/WarningActivity.java b/addons/sleep-timer/app/src/main/java/io/github/luyzfernando08/sleeptimer/WarningActivity.java
new file mode 100644
index 000000000..9f76a0c79
--- /dev/null
+++ b/addons/sleep-timer/app/src/main/java/io/github/luyzfernando08/sleeptimer/WarningActivity.java
@@ -0,0 +1,85 @@
+package io.github.luyzfernando08.sleeptimer;
+
+import android.app.Activity;
+import android.graphics.Color;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Looper;
+import android.view.Gravity;
+import android.widget.FrameLayout;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+/** The last minute: a countdown box over whatever is playing. Nobody answering means sleep at zero. */
+public class WarningActivity extends Activity {
+ private final Handler handler = new Handler(Looper.getMainLooper());
+ private TextView seconds;
+
+ private final Runnable tick = new Runnable() {
+ @Override
+ public void run() {
+ long end = Timer.end(WarningActivity.this);
+ if (end == 0) { // cancelled or pushed back elsewhere
+ finish();
+ return;
+ }
+ long left = (end - System.currentTimeMillis() + 999) / 1000;
+ if (left <= 0) {
+ Timer.sleepNow(WarningActivity.this);
+ finish();
+ return;
+ }
+ seconds.setText(getString(R.string.warning_seconds, left));
+ handler.postDelayed(this, 1000);
+ }
+ };
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ LinearLayout box = new LinearLayout(this);
+ box.setOrientation(LinearLayout.VERTICAL);
+ box.setGravity(Gravity.CENTER_HORIZONTAL);
+ box.setBackground(Ui.pill(this, 0xF2161826));
+ int pad = Ui.dp(this, 36);
+ box.setPadding(pad, pad, pad, pad);
+
+ TextView title = Ui.text(this, 30, Color.WHITE);
+ title.setText(R.string.warning_title);
+ box.addView(title);
+ seconds = Ui.text(this, 22, 0xFFB9B2FF);
+ seconds.setPadding(0, Ui.dp(this, 6), 0, Ui.dp(this, 14));
+ box.addView(seconds);
+ TextView more = Ui.row(box, 420);
+ more.setText(R.string.more);
+ more.setOnClickListener(v -> {
+ Timer.start(this, 15);
+ finish();
+ });
+ TextView now = Ui.row(box, 420);
+ now.setText(R.string.now);
+ now.setOnClickListener(v -> {
+ Timer.sleepNow(this);
+ finish();
+ });
+
+ FrameLayout root = new FrameLayout(this);
+ root.addView(box, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
+ FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER));
+ setContentView(root);
+ more.requestFocus();
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ handler.post(tick);
+ }
+
+ @Override
+ protected void onPause() {
+ // Back or Home leaves the warning, not the timer: the sleep alarm still fires at the end.
+ handler.removeCallbacks(tick);
+ super.onPause();
+ }
+}
diff --git a/addons/sleep-timer/app/src/main/res/drawable/banner.xml b/addons/sleep-timer/app/src/main/res/drawable/banner.xml
new file mode 100644
index 000000000..d57f61b8c
--- /dev/null
+++ b/addons/sleep-timer/app/src/main/res/drawable/banner.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- A crescent moon over a small clock face, on a night-blue tile. -->
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="320dp"
+ android:height="180dp"
+ android:viewportWidth="320"
+ android:viewportHeight="180">
+ <path android:fillColor="#141631" android:pathData="M0,0h320v180h-320z" />
+ <!-- moon -->
+ <path android:fillColor="#E9E4FF"
+ android:pathData="M150,40 A50,50 0,1 0 200,120 A40,40 0,1 1 150,40 Z" />
+ <!-- clock -->
+ <path android:fillColor="#7A6FF0" android:pathData="M210,118m-26,0a26,26 0,1 1 52,0a26,26 0,1 1 -52,0" />
+ <path android:strokeColor="#FFFFFF" android:strokeWidth="5" android:strokeLineCap="round"
+ android:pathData="M210,118 L210,102 M210,118 L222,124" />
+ <!-- stars -->
+ <path android:fillColor="#FFFFFF" android:pathData="M232,40m-3,0a3,3 0,1 1 6,0a3,3 0,1 1 -6,0" />
+ <path android:fillColor="#FFFFFF" android:pathData="M262,64m-2,0a2,2 0,1 1 4,0a2,2 0,1 1 -4,0" />
+ <path android:fillColor="#FFFFFF" android:pathData="M96,52m-2,0a2,2 0,1 1 4,0a2,2 0,1 1 -4,0" />
+</vector>
diff --git a/addons/sleep-timer/app/src/main/res/values-pt/strings.xml b/addons/sleep-timer/app/src/main/res/values-pt/strings.xml
new file mode 100644
index 000000000..52ea6106a
--- /dev/null
+++ b/addons/sleep-timer/app/src/main/res/values-pt/strings.xml
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Desligar</string>
+ <string name="hint">Escolha em quanto tempo a TV entra em espera. Um minuto antes aparece um aviso.</string>
+ <string name="in_minutes">%1$d min</string>
+ <string name="cancel">Cancelar o timer</string>
+ <string name="state_off">Nenhum timer ligado.</string>
+ <string name="state_on">Desliga às %1$s.</string>
+ <string name="no_service">O serviço de acessibilidade do Desligar está desligado (rode o script de instalação).</string>
+ <string name="warning_title">A TV vai desligar</string>
+ <string name="warning_seconds">em %1$d segundos</string>
+ <string name="more">Mais 15 minutos</string>
+ <string name="now">Desligar agora</string>
+ <string name="service_label">Desligar</string>
+ <string name="service_description">Só põe a TV em espera quando o timer do Desligar acaba. Não lê a tela.</string>
+</resources>
diff --git a/addons/sleep-timer/app/src/main/res/values/values.xml b/addons/sleep-timer/app/src/main/res/values/values.xml
new file mode 100644
index 000000000..daf399516
--- /dev/null
+++ b/addons/sleep-timer/app/src/main/res/values/values.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Sleep Timer</string>
+ <string name="hint">Choose when the TV goes to standby. A warning shows one minute before.</string>
+ <string name="in_minutes">%1$d min</string>
+ <string name="cancel">Cancel the timer</string>
+ <string name="state_off">No timer set.</string>
+ <string name="state_on">Standby at %1$s.</string>
+ <string name="no_service">The Sleep Timer accessibility service is off (run the install script).</string>
+ <string name="warning_title">The TV is turning off</string>
+ <string name="warning_seconds">in %1$d seconds</string>
+ <string name="more">15 more minutes</string>
+ <string name="now">Turn off now</string>
+ <string name="service_label">Sleep Timer</string>
+ <string name="service_description">Only puts the TV in standby when the Sleep Timer ends. It does not read the screen.</string>
+
+ <style name="Warning" parent="android:Theme.DeviceDefault.NoActionBar">
+ <item name="android:windowIsTranslucent">true</item>
+ <item name="android:windowBackground">@android:color/transparent</item>
+ <item name="android:backgroundDimEnabled">true</item>
+ <item name="android:windowAnimationStyle">@null</item>
+ </style>
+</resources>
diff --git a/addons/sleep-timer/app/src/main/res/xml/module_card.xml b/addons/sleep-timer/app/src/main/res/xml/module_card.xml
new file mode 100644
index 000000000..35bef3e70
--- /dev/null
+++ b/addons/sleep-timer/app/src/main/res/xml/module_card.xml
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="utf-8"?>
+<card spec="1" label="Sleep Timer" accent="#7A6FF0" />
diff --git a/addons/sleep-timer/app/src/main/res/xml/sleep_service.xml b/addons/sleep-timer/app/src/main/res/xml/sleep_service.xml
new file mode 100644
index 000000000..a6c592fc0
--- /dev/null
+++ b/addons/sleep-timer/app/src/main/res/xml/sleep_service.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- No events, no window content: the service only performs the lock-screen global action. -->
+<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
+ android:accessibilityEventTypes="typeAnnouncement"
+ android:accessibilityFeedbackType="feedbackGeneric"
+ android:canRetrieveWindowContent="false"
+ android:description="@string/service_description"
+ android:notificationTimeout="1000" />
diff --git a/addons/sleep-timer/build-and-install.ps1 b/addons/sleep-timer/build-and-install.ps1
new file mode 100644
index 000000000..68143a47c
--- /dev/null
+++ b/addons/sleep-timer/build-and-install.ps1
@@ -0,0 +1,44 @@
+# Windows version of build-and-install.sh: build Sleep Timer, install it on the TV and switch on its
+# accessibility service (only the lock-screen action, which puts the TV to standby) and the right to open its
+# warning over other apps.
+#
+# Usage: addons\sleep-timer\build-and-install.ps1 -TvHost 192.168.1.50
+# addons\sleep-timer\build-and-install.ps1 -TvHost 192.168.1.50 -Uninstall
+param(
+ [string]$TvHost = $env:TV_HOST,
+ [switch]$Uninstall
+)
+$ErrorActionPreference = 'Stop'
+if (-not $TvHost) { throw 'pass -TvHost <tv ip> or set $env:TV_HOST' }
+$env:TV_HOST = $TvHost
+$here = $PSScriptRoot
+$tools = Join-Path (Split-Path (Split-Path $here -Parent) -Parent) 'tools'
+$py = Join-Path $tools 'venv\Scripts\python.exe'
+if (-not (Test-Path $py)) { throw 'run: python -m venv tools\venv; tools\venv\Scripts\python.exe -m pip install -r tools\requirements.txt' }
+$pkg = 'io.github.luyzfernando08.sleeptimer'
+$svc = "$pkg/$pkg.SleepService"
+function Tv([string]$cmd) { & $py -I (Join-Path $tools 'tv.py') $cmd; if ($LASTEXITCODE) { throw "tv.py failed: $cmd" } }
+
+# No double quotes inside these commands: Windows PowerShell 5.1 mangles them on the way to python, and the
+# values have no spaces.
+if ($Uninstall) {
+ Tv ('s=$(settings get secure enabled_accessibility_services); s=$(echo :$s: | sed s#:SVC:#:#); s=${s#:}; s=${s%:}; if [ -z $s ]; then settings delete secure enabled_accessibility_services; else settings put secure enabled_accessibility_services $s; fi; pm uninstall PKG'.Replace('SVC', $svc).Replace('PKG', $pkg))
+ exit 0
+}
+
+Push-Location $here
+# javac notes go to stderr, which Windows PowerShell 5.1 turns into errors under 'Stop'.
+$ErrorActionPreference = 'Continue'
+try {
+ & .\gradlew.bat assembleRelease -q
+} finally {
+ Pop-Location
+}
+if ($LASTEXITCODE) { throw 'build failed (JDK 17 and Android SDK 34 needed; see launcher\README)' }
+$ErrorActionPreference = 'Stop'
+& $py -I (Join-Path $tools 'b64push.py') (Join-Path $here 'app\build\outputs\apk\release\app-release.apk') /data/local/tmp/sleeptimer.apk | Out-Null
+if ($LASTEXITCODE) { throw 'sending the APK failed; run this again' }
+Tv 'pm install -r /data/local/tmp/sleeptimer.apk; rm -f /data/local/tmp/sleeptimer.apk'
+Tv ('s=$(settings get secure enabled_accessibility_services); case :$s: in *:SVC:*) ;; *) if [ -z $s ] || [ $s = null ]; then s=SVC; else s=$s:SVC; fi; settings put secure enabled_accessibility_services $s;; esac; settings put secure accessibility_enabled 1'.Replace('SVC', $svc))
+Tv "appops set $pkg SYSTEM_ALERT_WINDOW allow; appops set $pkg SCHEDULE_EXACT_ALARM allow 2>/dev/null; true"
+Write-Host 'Installed. Pick a time on the Sleep Timer card.'
diff --git a/addons/sleep-timer/build-and-install.sh b/addons/sleep-timer/build-and-install.sh
new file mode 100755
index 000000000..e0a4fb835
--- /dev/null
+++ b/addons/sleep-timer/build-and-install.sh
@@ -0,0 +1,35 @@
+#!/usr/bin/env bash
+# Build Sleep Timer, install it on the TV and switch on its accessibility service (only the lock-screen action,
+# which puts the TV to standby) and the right to open its warning over other apps.
+#
+# Usage: TV_HOST=192.168.1.50 addons/sleep-timer/build-and-install.sh
+# TV_HOST=192.168.1.50 addons/sleep-timer/build-and-install.sh --uninstall
+# Try it without waiting (adb only): a 70 s timer, the warning after 10 s:
+# TV_HOST=192.168.1.50 tools/tv.py 'am broadcast -n io.github.luyzfernando08.sleeptimer/.AlarmReceiver -a io.github.luyzfernando08.sleeptimer.TEST --ei seconds 70'
+set -euo pipefail
+HERE="$(cd "$(dirname "$0")" && pwd)"
+TOOLS="$HERE/../../tools"
+: "${TV_HOST:?set TV_HOST to the TV IP address, e.g. TV_HOST=192.168.1.50 $0}"
+PY="$TOOLS/venv/bin/python"
+[ -x "$PY" ] || PY="$TOOLS/venv/Scripts/python.exe"
+[ -x "$PY" ] || { echo "run: python3 -m venv tools/venv && tools/venv/bin/pip install -r tools/requirements.txt" >&2; exit 1; }
+export MSYS_NO_PATHCONV=1
+PKG=io.github.luyzfernando08.sleeptimer
+SVC=$PKG/$PKG.SleepService
+tv() { "$PY" -I "$TOOLS/tv.py" "$@"; }
+
+if [ "${1:-}" = --uninstall ]; then
+ # Take the service out of the enabled list, keeping any others, then remove the app.
+ tv "s=\$(settings get secure enabled_accessibility_services); s=\$(echo \":\$s:\" | sed 's#:$SVC:#:#; s#^:##; s#:\$##'); if [ -z \"\$s\" ]; then settings delete secure enabled_accessibility_services; else settings put secure enabled_accessibility_services \$s; fi; pm uninstall $PKG"
+ exit 0
+fi
+
+(cd "$HERE" && ./gradlew assembleRelease -q) || { echo "build failed (JDK 17 and Android SDK 34 needed; see launcher/README)" >&2; exit 1; }
+"$PY" -I "$TOOLS/b64push.py" "$HERE/app/build/outputs/apk/release/app-release.apk" /data/local/tmp/sleeptimer.apk >/dev/null
+tv "pm install -r /data/local/tmp/sleeptimer.apk; rm -f /data/local/tmp/sleeptimer.apk"
+# Add the service to the enabled list without switching off the ones already there.
+tv "s=\$(settings get secure enabled_accessibility_services); case :\$s: in *:$SVC:*) ;; *) if [ -z \$s ] || [ \$s = null ]; then s=$SVC; else s=\$s:$SVC; fi; settings put secure enabled_accessibility_services \$s;; esac; settings put secure accessibility_enabled 1"
+# Android 10 and later only let an app open its warning from the background when it may draw over other apps;
+# Android 12 and later need the exact-alarm grant for the timer to fire on the minute.
+tv "appops set $PKG SYSTEM_ALERT_WINDOW allow; appops set $PKG SCHEDULE_EXACT_ALARM allow 2>/dev/null; true"
+echo "Installed. Pick a time on the Sleep Timer card."
diff --git a/addons/sleep-timer/build.gradle b/addons/sleep-timer/build.gradle
new file mode 100644
index 000000000..48978475f
--- /dev/null
+++ b/addons/sleep-timer/build.gradle
@@ -0,0 +1,3 @@
+plugins {
+ id 'com.android.application' version '8.5.2' apply false
+}
diff --git a/addons/sleep-timer/gradle.properties b/addons/sleep-timer/gradle.properties
new file mode 100644
index 000000000..18825f968
--- /dev/null
+++ b/addons/sleep-timer/gradle.properties
@@ -0,0 +1,3 @@
+org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
+android.useAndroidX=true
+android.nonTransitiveRClass=true
diff --git a/addons/sleep-timer/gradlew b/addons/sleep-timer/gradlew
new file mode 100755
index 000000000..fbcfb4bcb
--- /dev/null
+++ b/addons/sleep-timer/gradlew
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Reuse the repository's pinned Gradle distribution, but build this independent project.
+addon_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) || exit 1
+exec sh "$addon_dir/../../launcher/gradlew" -p "$addon_dir" "$@"
diff --git a/addons/sleep-timer/gradlew.bat b/addons/sleep-timer/gradlew.bat
new file mode 100644
index 000000000..42f222173
--- /dev/null
+++ b/addons/sleep-timer/gradlew.bat
@@ -0,0 +1,3 @@
+@echo off
+rem Reuse the repository wrapper; this add-on remains its own Gradle project.
+call "%~dp0..\..\launcher\gradlew.bat" -p "%~dp0." %*
diff --git a/addons/sleep-timer/settings.gradle b/addons/sleep-timer/settings.gradle
new file mode 100644
index 000000000..b5817eebc
--- /dev/null
+++ b/addons/sleep-timer/settings.gradle
@@ -0,0 +1,16 @@
+pluginManagement {
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+dependencyResolutionManagement {
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+rootProject.name = "sleeptimer"
+include ':app'