From 999d08210384e6bbc8e61b2a15f33d5b4272d977 Mon Sep 17 00:00:00 2001 From: LeanBitLab Date: Fri, 20 Nov 2026 15:05:22 +0530 Subject: [PATCH] fix: stability pass for weather, keep-alive, screen time and widget updates - Store Breezy weather from the Gadgetbridge broadcast before rendering; weather previously never reached the widget - Keep-alive on Android 14+: request Physical activity (required by the health FGS type) and revert the switch with a message if denied, instead of failing silently with a SecurityException - Screen time: count exact foreground intervals since local midnight from usage events, excluding the launcher; incremental and cached per tick - Skip the weather JSON parse on partial widget updates - Localize "No Title" and "0m"; check_strings.py now checks cursor reads - Remove dead manifest actions (internal, CONFIGURATION_CHANGED, LOCKED_BOOT_COMPLETED) and look up widget ids only when handled --- app/src/main/AndroidManifest.xml | 9 +- .../com/leanbitlab/lwidget/AwidgetProvider.kt | 23 ++-- .../com/leanbitlab/lwidget/MainActivity.kt | 2 + .../leanbitlab/lwidget/SettingsPermissions.kt | 26 +++- .../com/leanbitlab/lwidget/SetupActivity.kt | 13 +- .../leanbitlab/lwidget/StepCounterService.kt | 56 ++++---- .../lwidget/calendar/CalendarFetcher.kt | 2 +- .../lwidget/render/WidgetRenderer.kt | 8 +- .../lwidget/stats/ScreenTimeTracker.kt | 122 ++++++++++++++++++ .../lwidget/stats/SystemStatsFetcher.kt | 43 ++---- .../leanbitlab/lwidget/tasks/TasksFetcher.kt | 2 +- app/src/main/res/values-ar/strings.xml | 2 + app/src/main/res/values-de/strings.xml | 2 + app/src/main/res/values-es/strings.xml | 2 + app/src/main/res/values-fr/strings.xml | 2 + app/src/main/res/values-hi/strings.xml | 2 + app/src/main/res/values-ja/strings.xml | 2 + app/src/main/res/values-pt/strings.xml | 2 + app/src/main/res/values-ru/strings.xml | 2 + app/src/main/res/values-tr/strings.xml | 2 + app/src/main/res/values-zh/strings.xml | 2 + app/src/main/res/values/strings.xml | 2 + .../lwidget/ScreenTimeTrackerTest.kt | 54 ++++++++ .../lwidget/WeatherBroadcastTest.kt | 44 +++++++ scripts/check_strings.py | 2 +- 25 files changed, 339 insertions(+), 89 deletions(-) create mode 100644 app/src/main/java/com/leanbitlab/lwidget/stats/ScreenTimeTracker.kt create mode 100644 app/src/test/java/com/leanbitlab/lwidget/ScreenTimeTrackerTest.kt create mode 100644 app/src/test/java/com/leanbitlab/lwidget/WeatherBroadcastTest.kt diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 29480b6..b809974 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -17,6 +17,11 @@ + + + + + @@ -73,13 +78,9 @@ - - - - diff --git a/app/src/main/java/com/leanbitlab/lwidget/AwidgetProvider.kt b/app/src/main/java/com/leanbitlab/lwidget/AwidgetProvider.kt index b5a470d..2bcb77c 100644 --- a/app/src/main/java/com/leanbitlab/lwidget/AwidgetProvider.kt +++ b/app/src/main/java/com/leanbitlab/lwidget/AwidgetProvider.kt @@ -14,6 +14,7 @@ import com.leanbitlab.lwidget.calendar.CalendarFetcher import com.leanbitlab.lwidget.render.WidgetRenderer import com.leanbitlab.lwidget.stats.SystemStatsFetcher import com.leanbitlab.lwidget.tasks.TasksFetcher +import com.leanbitlab.lwidget.weather.BreezyWeatherFetcher import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -104,13 +105,15 @@ class AwidgetProvider : AppWidgetProvider() { override fun onReceive(context: Context, intent: Intent) { super.onReceive(context, intent) - val appWidgetManager = AppWidgetManager.getInstance(context) - val thisAppWidget = ComponentName(context, AwidgetProvider::class.java) - val appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidget) + // Weather arrives only through this broadcast: persist it before rendering + if (intent.action == ACTION_GENERIC_WEATHER) { + val weatherJson = intent.getStringExtra(EXTRA_WEATHER_JSON) + if (weatherJson.isNullOrEmpty()) return + BreezyWeatherFetcher.saveLatestWeatherData(context, weatherJson) + } val isBootOrReplaced = intent.action in listOf( Intent.ACTION_BOOT_COMPLETED, - Intent.ACTION_LOCKED_BOOT_COMPLETED, Intent.ACTION_MY_PACKAGE_REPLACED, "android.intent.action.QUICKBOOT_POWERON", "com.htc.intent.action.QUICKBOOT_POWERON" @@ -122,16 +125,17 @@ class AwidgetProvider : AppWidgetProvider() { } if (isBootOrReplaced || intent.action in listOf( - Intent.ACTION_CONFIGURATION_CHANGED, ACTION_BATTERY_UPDATE, StepCounterService.ACTION_STEP_UPDATE, Intent.ACTION_PROVIDER_CHANGED, AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED, - "nodomain.freeyourgadget.gadgetbridge.ACTION_GENERIC_WEATHER" + ACTION_GENERIC_WEATHER )) { runAsync("broadcast ${intent.action}") { + val appWidgetManager = AppWidgetManager.getInstance(context) + val appWidgetIds = appWidgetManager.getAppWidgetIds(ComponentName(context, AwidgetProvider::class.java)) when { - isBootOrReplaced || intent.action == Intent.ACTION_CONFIGURATION_CHANGED -> { + isBootOrReplaced -> { scheduleWork(context) appWidgetIds.forEach { updateAppWidget(context, appWidgetManager, it, UpdateMode.FULL) } } @@ -152,7 +156,7 @@ class AwidgetProvider : AppWidgetProvider() { appWidgetIds.forEach { updateAppWidget(context, appWidgetManager, it, UpdateMode.CALENDAR_ONLY) } } } - intent.action == "nodomain.freeyourgadget.gadgetbridge.ACTION_GENERIC_WEATHER" -> { + intent.action == ACTION_GENERIC_WEATHER -> { appWidgetIds.forEach { updateAppWidget(context, appWidgetManager, it, UpdateMode.FULL) } } } @@ -210,6 +214,9 @@ class AwidgetProvider : AppWidgetProvider() { } const val ACTION_NOOP = "com.leanbitlab.lwidget.ACTION_NOOP" + /** Gadgetbridge weather broadcast sent by Breezy Weather; payload is the JSON extra. */ + const val ACTION_GENERIC_WEATHER = "nodomain.freeyourgadget.gadgetbridge.ACTION_GENERIC_WEATHER" + const val EXTRA_WEATHER_JSON = "WeatherJson" const val ACTION_BATTERY_UPDATE = SystemStatsFetcher.ACTION_BATTERY_UPDATE const val PERMISSION_READ_TASKS_ORG = TasksFetcher.PERMISSION_READ_TASKS_ORG const val PERMISSION_READ_TASKS_ASTRID = TasksFetcher.PERMISSION_READ_TASKS_ASTRID diff --git a/app/src/main/java/com/leanbitlab/lwidget/MainActivity.kt b/app/src/main/java/com/leanbitlab/lwidget/MainActivity.kt index d0b1529..eb008cb 100644 --- a/app/src/main/java/com/leanbitlab/lwidget/MainActivity.kt +++ b/app/src/main/java/com/leanbitlab/lwidget/MainActivity.kt @@ -360,6 +360,8 @@ class MainActivity : AppCompatActivity() { updateWidget() updateToggleAvailability() } + } else if (requestCode == REQUEST_KEEP_ALIVE_PERMISSIONS) { + onKeepAlivePermissionsResult() } else if (requestCode == 103) { // Breezy Weather permission result if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { diff --git a/app/src/main/java/com/leanbitlab/lwidget/SettingsPermissions.kt b/app/src/main/java/com/leanbitlab/lwidget/SettingsPermissions.kt index e120183..8f49c34 100644 --- a/app/src/main/java/com/leanbitlab/lwidget/SettingsPermissions.kt +++ b/app/src/main/java/com/leanbitlab/lwidget/SettingsPermissions.kt @@ -189,11 +189,13 @@ internal fun MainActivity.setupKeepAliveSection() { .edit().putBoolean("keep_alive", isChecked).apply() if (isChecked) { - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU && - ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { - ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.POST_NOTIFICATIONS), 105) + val missing = StepCounterService.missingKeepAlivePermissions(this) + if (missing.isNotEmpty()) { + // Service starts (or the switch reverts) in onRequestPermissionsResult + ActivityCompat.requestPermissions(this, missing, REQUEST_KEEP_ALIVE_PERMISSIONS) + } else { + StepCounterService.startServiceIfEnabled(this) } - StepCounterService.startServiceIfEnabled(this) } else { if (!StepCounterService.isStepOrKeepAliveEnabled(this)) { stopService(Intent(this, StepCounterService::class.java)) @@ -204,6 +206,22 @@ internal fun MainActivity.setupKeepAliveSection() { } } +internal const val REQUEST_KEEP_ALIVE_PERMISSIONS = 105 + +/** After the keep-alive permission prompt: start the service, or turn keep-alive off if it cannot run. */ +internal fun MainActivity.onKeepAlivePermissionsResult() { + if (StepCounterService.canStart(this)) { + StepCounterService.startServiceIfEnabled(this) + return + } + prefs.edit().putBoolean("keep_alive", false).apply() + getSharedPreferences("com.leanbitlab.lwidget.PREFS", Context.MODE_PRIVATE) + .edit().putBoolean("keep_alive", false).apply() + findViewById(R.id.row_keep_alive_toggle) + ?.findViewById(R.id.row_switch)?.isChecked = false + android.widget.Toast.makeText(this, R.string.msg_keep_alive_needs_activity, android.widget.Toast.LENGTH_LONG).show() +} + internal fun MainActivity.setupBatteryOptimizationSection() { val row = findViewById(R.id.row_battery_optimization_toggle) val tvTitle = row.findViewById(R.id.row_label) diff --git a/app/src/main/java/com/leanbitlab/lwidget/SetupActivity.kt b/app/src/main/java/com/leanbitlab/lwidget/SetupActivity.kt index f9e01c4..353d6e3 100644 --- a/app/src/main/java/com/leanbitlab/lwidget/SetupActivity.kt +++ b/app/src/main/java/com/leanbitlab/lwidget/SetupActivity.kt @@ -31,6 +31,11 @@ class SetupActivity : AppCompatActivity() { ActivityResultContracts.RequestMultiplePermissions() ) { _ -> updatePermissionButtons() + // Keep-alive cannot run without its permissions (Android 14+): revert the switch + if (prefs.getBoolean("keep_alive", false) && !StepCounterService.canStart(this)) { + findViewById(R.id.switch_setup_keep_alive).isChecked = false + android.widget.Toast.makeText(this, R.string.msg_keep_alive_needs_activity, android.widget.Toast.LENGTH_LONG).show() + } } override fun onCreate(savedInstanceState: Bundle?) { @@ -76,13 +81,11 @@ class SetupActivity : AppCompatActivity() { val switchKeepAlive = findViewById(R.id.switch_setup_keep_alive) switchKeepAlive.isChecked = prefs.getBoolean("keep_alive", false) switchKeepAlive.setOnCheckedChangeListener { _, isChecked -> + prefs.edit().putBoolean("keep_alive", isChecked).apply() if (isChecked) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && - ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { - requestPermissionLauncher.launch(arrayOf(Manifest.permission.POST_NOTIFICATIONS)) - } + val missing = StepCounterService.missingKeepAlivePermissions(this) + if (missing.isNotEmpty()) requestPermissionLauncher.launch(missing) } - prefs.edit().putBoolean("keep_alive", isChecked).apply() } // Permissions Setup diff --git a/app/src/main/java/com/leanbitlab/lwidget/StepCounterService.kt b/app/src/main/java/com/leanbitlab/lwidget/StepCounterService.kt index 8548cb9..9529422 100644 --- a/app/src/main/java/com/leanbitlab/lwidget/StepCounterService.kt +++ b/app/src/main/java/com/leanbitlab/lwidget/StepCounterService.kt @@ -113,22 +113,36 @@ class StepCounterService : Service(), SensorEventListener { return false } - fun startServiceIfEnabled(context: Context) { - if (!isStepOrKeepAliveEnabled(context)) return - - val showSteps = isStepsVisibleAnywhere(context) - val hasActivityPerm = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + private fun hasActivityPermission(context: Context): Boolean = + Build.VERSION.SDK_INT < Build.VERSION_CODES.Q || ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACTIVITY_RECOGNITION) == android.content.pm.PackageManager.PERMISSION_GRANTED - } else { - true - } - // If only steps are enabled and activity permission is missing, do not start - if (showSteps && !hasActivityPerm) { - val globalPrefs = context.getSharedPreferences("com.leanbitlab.lwidget.PREFS", Context.MODE_PRIVATE) - val keepAlive = globalPrefs.getBoolean("keep_alive", false) - if (!keepAlive) return + /** + * Whether the foreground service may run. It uses the health FGS type, which Android 14+ + * refuses without ACTIVITY_RECOGNITION (SecurityException), even for keep-alive alone. + * Before 14, keep-alive can run without it; steps never can. + */ + fun canStart(context: Context): Boolean { + if (!isStepOrKeepAliveEnabled(context)) return false + if (hasActivityPermission(context)) return true + val keepAlive = context.getSharedPreferences("com.leanbitlab.lwidget.PREFS", Context.MODE_PRIVATE) + .getBoolean("keep_alive", false) + return keepAlive && Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE + } + + /** Runtime permissions still missing for keep-alive's foreground service. */ + fun missingKeepAlivePermissions(context: Context): Array = buildList { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && + ContextCompat.checkSelfPermission(context, android.Manifest.permission.POST_NOTIFICATIONS) != android.content.pm.PackageManager.PERMISSION_GRANTED) { + add(android.Manifest.permission.POST_NOTIFICATIONS) + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE && !hasActivityPermission(context)) { + add(android.Manifest.permission.ACTIVITY_RECOGNITION) } + }.toTypedArray() + + fun startServiceIfEnabled(context: Context) { + if (!canStart(context)) return try { val serviceIntent = Intent(context, StepCounterService::class.java) @@ -161,22 +175,11 @@ class StepCounterService : Service(), SensorEventListener { return } - val showSteps = isStepsVisibleAnywhere(this) - val isNeeded = isStepOrKeepAliveEnabled(this) - - // If steps is explicitly enabled, require ACTIVITY_RECOGNITION - val hasActivityPerm = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACTIVITY_RECOGNITION) == android.content.pm.PackageManager.PERMISSION_GRANTED - if (showSteps && !hasActivityPerm) { - val keepAlive = prefs.getBoolean("keep_alive", false) - if (!keepAlive) { - stopSelf() - return - } - } - if (!isNeeded) { + if (!canStart(this)) { stopSelf() return } + val hasActivityPerm = hasActivityPermission(this) sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager stepSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER) @@ -191,7 +194,6 @@ class StepCounterService : Service(), SensorEventListener { val filter = android.content.IntentFilter().apply { addAction(Intent.ACTION_BATTERY_CHANGED) addAction(Intent.ACTION_TIME_TICK) - addAction(Intent.ACTION_CONFIGURATION_CHANGED) addAction(Intent.ACTION_SCREEN_ON) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { diff --git a/app/src/main/java/com/leanbitlab/lwidget/calendar/CalendarFetcher.kt b/app/src/main/java/com/leanbitlab/lwidget/calendar/CalendarFetcher.kt index 57d38d3..b6f96ee 100644 --- a/app/src/main/java/com/leanbitlab/lwidget/calendar/CalendarFetcher.kt +++ b/app/src/main/java/com/leanbitlab/lwidget/calendar/CalendarFetcher.kt @@ -176,7 +176,7 @@ object CalendarFetcher { while (cursor.moveToNext() && events.size < 10) { val eventId = cursor.getLong(eventIdIdx) - val title = cursor.getString(titleIdx) ?: "No Title" + val title = cursor.getString(titleIdx) ?: context.getString(R.string.widget_no_title) val begin = cursor.getLong(beginIdx) val end = cursor.getLong(endIdx) val calId = cursor.getLong(calIdIdx) diff --git a/app/src/main/java/com/leanbitlab/lwidget/render/WidgetRenderer.kt b/app/src/main/java/com/leanbitlab/lwidget/render/WidgetRenderer.kt index 2f4daff..79d4da5 100644 --- a/app/src/main/java/com/leanbitlab/lwidget/render/WidgetRenderer.kt +++ b/app/src/main/java/com/leanbitlab/lwidget/render/WidgetRenderer.kt @@ -112,9 +112,6 @@ object WidgetRenderer { } val sizeEvents = prefs.getFloat("size_events", 14f) - val bweather = if (showWeatherCondition) { - com.leanbitlab.lwidget.weather.BreezyWeatherFetcher.fetchLocalWeather(context) - } else null val showWeatherIconOnly = prefs.getBoolean("show_weather_icon_only", false) val useDynamicColors = prefs.getBoolean("use_dynamic_colors", true) @@ -236,6 +233,11 @@ object WidgetRenderer { return alarmViews } + // Full render only: partial updates above never touch weather, so skip the JSON parse + val bweather = if (showWeatherCondition) { + com.leanbitlab.lwidget.weather.BreezyWeatherFetcher.fetchLocalWeather(context) + } else null + val views = RemoteViews(context.packageName, layoutId) // Background & Outline diff --git a/app/src/main/java/com/leanbitlab/lwidget/stats/ScreenTimeTracker.kt b/app/src/main/java/com/leanbitlab/lwidget/stats/ScreenTimeTracker.kt new file mode 100644 index 0000000..86c0312 --- /dev/null +++ b/app/src/main/java/com/leanbitlab/lwidget/stats/ScreenTimeTracker.kt @@ -0,0 +1,122 @@ +package com.leanbitlab.lwidget.stats + +import android.app.usage.UsageEvents +import android.app.usage.UsageStatsManager +import android.content.Context +import java.time.LocalDate +import java.time.ZoneId + +/** + * Today's app foreground time, counted from usage events since local midnight. + * + * queryUsageStats(INTERVAL_DAILY) returns whole daily buckets that are not aligned to local + * midnight, so it counts part of yesterday. Events give exact intervals. To keep the per-minute + * tick cheap, the running total is cached and only events since the last call are read. + */ +object ScreenTimeTracker { + + // UsageEvents.Event constants by value: some names need API 28/29, minSdk is 26 + private const val ACTIVITY_RESUMED = 1 // MOVE_TO_FOREGROUND + private const val ACTIVITY_PAUSED = 2 // MOVE_TO_BACKGROUND + private const val SCREEN_NON_INTERACTIVE = 16 + private const val DEVICE_SHUTDOWN = 26 + + private const val DAY_MS = 86_400_000L + private const val PREFS = "com.leanbitlab.lwidget.SCREEN_TIME" // i18n-ignore + + data class Event(val type: Int, val pkg: String, val time: Long) + + /** Running state for one day. [openPkg]/[openStart] describe the app in the foreground now. */ + data class State( + val day: String, + val processedUntil: Long, + val totalMs: Long, + val openPkg: String? = null, + val openStart: Long = 0L + ) { + /** Total including the still-open interval up to [now]. */ + fun totalAt(now: Long): Long = totalMs + if (openPkg != null) (now - openStart).coerceAtLeast(0) else 0 + } + + /** Applies [events] (in time order) to [state]. Pure, so it is unit-tested directly. */ + fun fold(state: State, events: List, excludedPkg: String?): State { + var total = state.totalMs + var openPkg = state.openPkg + var openStart = state.openStart + fun close(at: Long) { + if (openPkg != null) total += (at - openStart).coerceAtLeast(0) + openPkg = null + } + for (e in events) { + when (e.type) { + ACTIVITY_RESUMED -> { + close(e.time) + if (e.pkg != excludedPkg) { + openPkg = e.pkg + openStart = e.time + } + } + ACTIVITY_PAUSED -> if (e.pkg == openPkg) close(e.time) + SCREEN_NON_INTERACTIVE, DEVICE_SHUTDOWN -> close(e.time) + } + } + return state.copy(totalMs = total, openPkg = openPkg, openStart = openStart) + } + + /** Foreground time today in ms. Synchronized: several widgets may update at once. */ + @Synchronized + fun todayForegroundMs(context: Context, now: Long = System.currentTimeMillis()): Long { + val zone = ZoneId.systemDefault() + val today = LocalDate.now(zone) + val midnight = today.atStartOfDay(zone).toInstant().toEpochMilli() + val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + + var state = State( + day = prefs.getString("day", "") ?: "", + processedUntil = prefs.getLong("processed_until", 0L), + totalMs = prefs.getLong("total_ms", 0L), + openPkg = prefs.getString("open_pkg", null), + openStart = prefs.getLong("open_start", 0L) + ) + val usm = context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager + val launcher = defaultLauncher(context) + if (state.day != today.toString() || state.processedUntil !in midnight..now) { + // New day: replay the gap up to midnight so an app still open then counts from midnight + val bridged = if (state.day.isNotEmpty() && state.processedUntil in (midnight - DAY_MS) until midnight) { + fold(state, readEvents(usm, state.processedUntil, midnight), launcher).openPkg + } else null + state = State(today.toString(), midnight, 0L, bridged, midnight) + } + state = fold(state, readEvents(usm, state.processedUntil, now), launcher).copy(processedUntil = now) + + prefs.edit() + .putString("day", state.day) + .putLong("processed_until", state.processedUntil) + .putLong("total_ms", state.totalMs) + .putString("open_pkg", state.openPkg) + .putLong("open_start", state.openStart) + .apply() + return state.totalAt(now) + } + + private fun readEvents(usm: UsageStatsManager, from: Long, to: Long): List { + val events = ArrayList() + val iter = usm.queryEvents(from, to) ?: return events + val e = UsageEvents.Event() + while (iter.hasNextEvent()) { + iter.getNextEvent(e) + when (e.eventType) { + ACTIVITY_RESUMED, ACTIVITY_PAUSED, SCREEN_NON_INTERACTIVE, DEVICE_SHUTDOWN -> + events.add(Event(e.eventType, e.packageName, e.timeStamp)) + } + } + return events + } + + /** The home screen is not app usage (Digital Wellbeing excludes it too). */ + private fun defaultLauncher(context: Context): String? { + val home = android.content.Intent(android.content.Intent.ACTION_MAIN).addCategory(android.content.Intent.CATEGORY_HOME) + return context.packageManager.resolveActivity(home, android.content.pm.PackageManager.MATCH_DEFAULT_ONLY) + ?.activityInfo?.packageName + } +} diff --git a/app/src/main/java/com/leanbitlab/lwidget/stats/SystemStatsFetcher.kt b/app/src/main/java/com/leanbitlab/lwidget/stats/SystemStatsFetcher.kt index 6567206..9f224df 100644 --- a/app/src/main/java/com/leanbitlab/lwidget/stats/SystemStatsFetcher.kt +++ b/app/src/main/java/com/leanbitlab/lwidget/stats/SystemStatsFetcher.kt @@ -5,7 +5,6 @@ import android.app.ActivityManager import android.app.AlarmManager import android.app.AppOpsManager import android.app.usage.NetworkStatsManager -import android.app.usage.UsageStatsManager import android.content.Context import android.content.Intent import android.content.IntentFilter @@ -138,43 +137,17 @@ object SystemStatsFetcher { return } - val usageStatsManager = context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager - - val calendar = java.util.Calendar.getInstance() - calendar.set(java.util.Calendar.HOUR_OF_DAY, 0) - calendar.set(java.util.Calendar.MINUTE, 0) - calendar.set(java.util.Calendar.SECOND, 0) - calendar.set(java.util.Calendar.MILLISECOND, 0) - - val startTime = calendar.timeInMillis - val endTime = System.currentTimeMillis() - - val stats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, startTime, endTime) - - var totalForegroundTime = 0L - if (stats != null) { - for (usage in stats) { - if (usage.totalTimeInForeground > 0) { - totalForegroundTime += usage.totalTimeInForeground - } - } - } + val totalForegroundTime = ScreenTimeTracker.todayForegroundMs(context) val isBold = prefs.getBoolean("bold_screen_time", false) - if (totalForegroundTime > 0) { - val totalMinutes = totalForegroundTime / (1000 * 60) - val hours = totalMinutes / 60 - val mins = totalMinutes % 60 - val timeString = if (hours > 0) context.getString(R.string.duration_hours_minutes, hours, mins) else context.getString(R.string.duration_minutes, mins) - val span = SpannableString(timeString) - if (isBold) span.setSpan(StyleSpan(Typeface.BOLD), 0, span.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) - views.setTextViewText(R.id.text_screen_time, span) - } else { - val span = SpannableString("0m") - if (isBold) span.setSpan(StyleSpan(Typeface.BOLD), 0, span.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) - views.setTextViewText(R.id.text_screen_time, span) - } + val totalMinutes = totalForegroundTime / (1000 * 60) + val hours = totalMinutes / 60 + val mins = totalMinutes % 60 + val timeString = if (hours > 0) context.getString(R.string.duration_hours_minutes, hours, mins) else context.getString(R.string.duration_minutes, mins) + val span = SpannableString(timeString) + if (isBold) span.setSpan(StyleSpan(Typeface.BOLD), 0, span.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) + views.setTextViewText(R.id.text_screen_time, span) } fun updateDataUsage(context: Context, views: RemoteViews, prefs: SharedPreferences) { diff --git a/app/src/main/java/com/leanbitlab/lwidget/tasks/TasksFetcher.kt b/app/src/main/java/com/leanbitlab/lwidget/tasks/TasksFetcher.kt index 14a92a3..6b46996 100644 --- a/app/src/main/java/com/leanbitlab/lwidget/tasks/TasksFetcher.kt +++ b/app/src/main/java/com/leanbitlab/lwidget/tasks/TasksFetcher.kt @@ -50,7 +50,7 @@ object TasksFetcher { continue } - val title = cursor.getString(titleIdx) ?: "No Title" + val title = cursor.getString(titleIdx) ?: context.getString(R.string.widget_no_title) tasks.add(TaskData(title, dueMillis)) } } diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 7d41067..5932a3b 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -115,6 +115,8 @@ إلغاء حسنًا تثبيت + يتطلب "الإبقاء قيد التشغيل" إذن النشاط البدني في إصدار Android هذا. + (بدون عنوان) تطبيق Breezy Weather (مع تفعيل DataBridge) مطلوب. تطبيق Breezy Weather مطلوب. تطبيق Tasks.org مطلوب لهذه الميزة. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index a170054..e667a1a 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -115,6 +115,8 @@ Abbrechen Verstanden Installieren + „Aktiv halten“ benötigt auf dieser Android-Version die Berechtigung für körperliche Aktivität. + (Kein Titel) Die App Breezy Weather (mit aktivierter DataBridge) ist erforderlich. Die App Breezy Weather ist erforderlich. Für diese Funktion ist die App Tasks.org erforderlich. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 7bd1a7e..c6e4d46 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -115,6 +115,8 @@ Cancelar Entendido Instalar + Mantener activo requiere el permiso de actividad física en esta versión de Android. + (Sin título) Se requiere la app Breezy Weather (con DataBridge activado). Se requiere la app Breezy Weather. Esta función requiere la app Tasks.org. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 262f2af..7405a63 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -115,6 +115,8 @@ Annuler Compris Installer + Le maintien actif nécessite l\'autorisation Activité physique sur cette version d\'Android. + (Sans titre) L\'application Breezy Weather (avec DataBridge activé) est requise. L\'application Breezy Weather est requise. L\'application Tasks.org est requise pour cette fonctionnalité. diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 8c6fdd6..f9c1c1f 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -115,6 +115,8 @@ रद्द करें समझ गया इंस्टॉल करें + इस Android संस्करण पर "सक्रिय रखें" के लिए शारीरिक गतिविधि अनुमति आवश्यक है। + (कोई शीर्षक नहीं) Breezy Weather ऐप (DataBridge चालू के साथ) आवश्यक है। Breezy Weather ऐप आवश्यक है। इस सुविधा के लिए Tasks.org ऐप आवश्यक है। diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 7440b74..470aedf 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -115,6 +115,8 @@ キャンセル 了解 インストール + このAndroidバージョンでは、バックグラウンド維持に身体活動の権限が必要です。 + (タイトルなし) Breezy Weather アプリ(DataBridge を有効にしたもの)が必要です。 Breezy Weather アプリが必要です。 この機能には Tasks.org アプリが必要です。 diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index eb148c6..c0ed1de 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -115,6 +115,8 @@ Cancelar Entendi Instalar + Manter ativo requer a permissão de atividade física nesta versão do Android. + (Sem título) O app Breezy Weather (com DataBridge ativado) é necessário. O app Breezy Weather é necessário. O app Tasks.org é necessário para este recurso. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 283c2b1..d44cc78 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -115,6 +115,8 @@ Отмена Понятно Установить + Для фоновой работы на этой версии Android нужно разрешение «Физическая активность». + (Без названия) Требуется приложение Breezy Weather (с включённым DataBridge). Требуется приложение Breezy Weather. Для этой функции требуется приложение Tasks.org. diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index 18b138a..0db6757 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -115,6 +115,8 @@ İptal Anladım Yükle + Bu Android sürümünde Arka Planda Tut için Fiziksel etkinlik izni gerekir. + (Başlıksız) Breezy Weather uygulaması (DataBridge etkin) gereklidir. Breezy Weather uygulaması gereklidir. Bu özellik için Tasks.org uygulaması gereklidir. diff --git a/app/src/main/res/values-zh/strings.xml b/app/src/main/res/values-zh/strings.xml index 1c33533..c7388ae 100644 --- a/app/src/main/res/values-zh/strings.xml +++ b/app/src/main/res/values-zh/strings.xml @@ -115,6 +115,8 @@ 取消 知道了 安装 + 在此 Android 版本上,后台保活需要“身体活动”权限。 + (无标题) 需要 Breezy Weather 应用(并启用 DataBridge)。 需要 Breezy Weather 应用。 此功能需要 Tasks.org 应用。 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 47e17f9..aa44a65 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -115,6 +115,8 @@ Cancel Got it Install + Keep Alive needs the Physical activity permission on this Android version. + (No title) Breezy Weather app (with DataBridge enabled) is required. Breezy Weather app is required. Tasks.org app is required for this feature. diff --git a/app/src/test/java/com/leanbitlab/lwidget/ScreenTimeTrackerTest.kt b/app/src/test/java/com/leanbitlab/lwidget/ScreenTimeTrackerTest.kt new file mode 100644 index 0000000..7fafa5a --- /dev/null +++ b/app/src/test/java/com/leanbitlab/lwidget/ScreenTimeTrackerTest.kt @@ -0,0 +1,54 @@ +package com.leanbitlab.lwidget + +import com.leanbitlab.lwidget.stats.ScreenTimeTracker +import com.leanbitlab.lwidget.stats.ScreenTimeTracker.Event +import com.leanbitlab.lwidget.stats.ScreenTimeTracker.State +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +/** Screen time is summed from exact foreground intervals, excluding the launcher. */ +class ScreenTimeTrackerTest { + + private val resumed = 1 + private val paused = 2 + private val screenOff = 16 + private val start = State("2026-11-20", 0L, 0L) + + @Test + fun sumsIntervalsAndSkipsLauncher() { + val s = ScreenTimeTracker.fold(start, listOf( + Event(resumed, "a", 1_000), Event(paused, "a", 4_000), + Event(resumed, "home", 4_000), Event(paused, "home", 9_000), + Event(resumed, "b", 9_000), Event(paused, "b", 10_000) + ), excludedPkg = "home") + assertEquals(4_000, s.totalMs) + assertNull(s.openPkg) + } + + @Test + fun openAppCountsUntilNowAndAcrossCalls() { + val first = ScreenTimeTracker.fold(start, listOf(Event(resumed, "a", 1_000)), null) + assertEquals(2_000, first.totalAt(3_000)) + // Next tick sees only new events; the open interval continues + val second = ScreenTimeTracker.fold(first, listOf(Event(paused, "a", 5_000)), null) + assertEquals(4_000, second.totalMs) + } + + @Test + fun screenOffClosesInterval() { + val s = ScreenTimeTracker.fold(start, listOf( + Event(resumed, "a", 1_000), Event(screenOff, "android", 2_000), Event(paused, "a", 60_000) + ), null) + assertEquals(1_000, s.totalMs) + } + + @Test + fun switchingAppsDoesNotDoubleCount() { + // Next app resumes before the previous one reports paused + val s = ScreenTimeTracker.fold(start, listOf( + Event(resumed, "a", 0), Event(resumed, "b", 3_000), Event(paused, "a", 3_100), Event(paused, "b", 5_000) + ), null) + assertEquals(5_000, s.totalMs) + } +} diff --git a/app/src/test/java/com/leanbitlab/lwidget/WeatherBroadcastTest.kt b/app/src/test/java/com/leanbitlab/lwidget/WeatherBroadcastTest.kt new file mode 100644 index 0000000..c789e4a --- /dev/null +++ b/app/src/test/java/com/leanbitlab/lwidget/WeatherBroadcastTest.kt @@ -0,0 +1,44 @@ +package com.leanbitlab.lwidget + +import android.content.Context +import android.content.Intent +import androidx.test.core.app.ApplicationProvider +import com.leanbitlab.lwidget.weather.BreezyWeatherFetcher +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config + +/** Breezy Weather sends data only via the Gadgetbridge broadcast; the provider must store it. */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class WeatherBroadcastTest { + + private val context = ApplicationProvider.getApplicationContext() + + private fun sendWeather(json: String?) { + val intent = Intent(context, AwidgetProvider::class.java).apply { + action = AwidgetProvider.ACTION_GENERIC_WEATHER + if (json != null) putExtra(AwidgetProvider.EXTRA_WEATHER_JSON, json) + } + context.sendBroadcast(intent) + shadowOf(android.os.Looper.getMainLooper()).idle() + } + + @Test + fun weatherBroadcastIsStored() { + sendWeather("""{"currentTemp":291,"currentCondition":"Cloudy"}""") + val data = BreezyWeatherFetcher.fetchLocalWeather(context) + assertEquals(291, data?.currentTemp) + assertEquals("Cloudy", data?.currentCondition) + } + + @Test + fun broadcastWithoutPayloadKeepsNothing() { + sendWeather(null) + assertNull(BreezyWeatherFetcher.fetchLocalWeather(context)) + } +} diff --git a/scripts/check_strings.py b/scripts/check_strings.py index c425eff..73b1cea 100644 --- a/scripts/check_strings.py +++ b/scripts/check_strings.py @@ -43,7 +43,7 @@ # Lines whose literals are never shown to users. NON_UI_LINE = re.compile( r"^\s*@[\w.:]+|Log\.[dviwe]\(|throw |Exception\(|const val|import |" - r"\.(get|put)(String|Int|Boolean|Long|Float|StringSet)\(|getSharedPreferences|" + r"(?