2 Commits
Author SHA1 Message Date
Vaishno Singh 153bf3598d fix(update): reliable background update notifications, dedicated AppUpdateWorker, intent handling (v1.2.2)
Build & Release Android APK / Build & Publish Release APK (push) Failing after 3m26s
2026-11-19 18:36:06 +05:30
Vaishno Singh 61e2b2445b fix(notifications): instant state transition polling, 2-stage verification to prevent false positives (v1.2.1)
Build & Release Android APK / Build & Publish Release APK (push) Failing after 3m28s
2026-11-19 17:56:34 +05:30
8 changed files with 211 additions and 43 deletions
+2 -2
View File
@@ -11,8 +11,8 @@ android {
applicationId = "com.expapp.trigger" applicationId = "com.expapp.trigger"
minSdk = 24 minSdk = 24
targetSdk = 34 targetSdk = 34
versionCode = 14 versionCode = 16
versionName = "1.2.0" versionName = "1.2.2"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables { vectorDrawables {
@@ -39,6 +39,7 @@ import com.expapp.trigger.ui.theme.DarkBackground
import com.expapp.trigger.ui.theme.ExpAppTheme import com.expapp.trigger.ui.theme.ExpAppTheme
import com.expapp.trigger.widget.ServerWidgetProvider import com.expapp.trigger.widget.ServerWidgetProvider
import com.expapp.trigger.worker.ActionTriggerWorker import com.expapp.trigger.worker.ActionTriggerWorker
import com.expapp.trigger.worker.AppUpdateWorker
import com.expapp.trigger.worker.NotificationHelper import com.expapp.trigger.worker.NotificationHelper
import com.expapp.trigger.worker.ServerMonitorWorker import com.expapp.trigger.worker.ServerMonitorWorker
@@ -62,6 +63,7 @@ class MainActivity : FragmentActivity() {
NotificationHelper.createNotificationChannel(this) NotificationHelper.createNotificationChannel(this)
if (appSettings.isBackgroundMonitoringEnabled) { if (appSettings.isBackgroundMonitoringEnabled) {
ServerMonitorWorker.schedule(this) ServerMonitorWorker.schedule(this)
AppUpdateWorker.schedule(this)
} }
onNotificationPermissionGrantedCallback?.invoke() onNotificationPermissionGrantedCallback?.invoke()
} else { } else {
@@ -127,9 +129,10 @@ class MainActivity : FragmentActivity() {
} }
} }
// Initialize background server monitoring // Initialize background server monitoring & update checks
if (appSettings.isBackgroundMonitoringEnabled) { if (appSettings.isBackgroundMonitoringEnabled) {
ServerMonitorWorker.schedule(this) ServerMonitorWorker.schedule(this)
AppUpdateWorker.schedule(this)
} }
// Handle initial launch intent (from NFC or Widget) // Handle initial launch intent (from NFC or Widget)
@@ -195,10 +198,12 @@ class MainActivity : FragmentActivity() {
override fun onStop() { override fun onStop() {
super.onStop() super.onStop()
// When leaving the app, trigger an immediate one-time check & ensure worker is scheduled // When leaving the app, trigger an immediate one-time check & ensure workers are scheduled
if (appSettings.isBackgroundMonitoringEnabled) { if (appSettings.isBackgroundMonitoringEnabled) {
ServerMonitorWorker.runOnce(this) ServerMonitorWorker.runOnce(this)
ServerMonitorWorker.schedule(this) ServerMonitorWorker.schedule(this)
AppUpdateWorker.runOnce(this)
AppUpdateWorker.schedule(this)
} }
} }
@@ -248,8 +248,16 @@ class TriggerClient(
} }
} }
} }
// If targetNode not matched or not provided, fallback to root or first entry if (matchedObj != null) {
matchedObj ?: if (nodesObj.size() > 0) nodesObj.entrySet().first().value.asJsonObject else rootJson matchedObj
} else if (targetNode.isNotBlank()) {
// Node explicitly configured but missing from sentinel nodes map
return NodeStatus(isOnline = false, statusText = "UNKNOWN NODE", isReachable = true)
} else if (nodesObj.size() > 0) {
nodesObj.entrySet().first().value.asJsonObject
} else {
rootJson
}
} else { } else {
rootJson rootJson
} }
@@ -258,7 +266,7 @@ class TriggerClient(
json.has("online") && json.get("online").isJsonPrimitive && json.get("online").asJsonPrimitive.isBoolean -> json.has("online") && json.get("online").isJsonPrimitive && json.get("online").asJsonPrimitive.isBoolean ->
json.get("online").asBoolean json.get("online").asBoolean
json.has("status") && json.get("status").isJsonPrimitive -> json.has("status") && json.get("status").isJsonPrimitive ->
json.get("status").asString.equals("online", ignoreCase = true) json.get("status").asString.trim().equals("online", ignoreCase = true)
else -> false else -> false
} }
val ip = if (json.has("ip") && !json.get("ip").isJsonNull) json.get("ip").asString else null val ip = if (json.has("ip") && !json.get("ip").isJsonNull) json.get("ip").asString else null
@@ -288,10 +296,10 @@ class TriggerClient(
isReachable = true isReachable = true
) )
} catch (e: Exception) { } catch (e: Exception) {
NodeStatus(isOnline = false, statusText = "ERROR", isReachable = true) NodeStatus(isOnline = false, statusText = "ERROR", isReachable = isHttpSuccess)
} }
} else if (isHttpSuccess) { } else if (isHttpSuccess) {
val isOnline = body.equals("ONLINE", ignoreCase = true) val isOnline = body.trim().equals("ONLINE", ignoreCase = true)
return NodeStatus(isOnline = isOnline, statusText = if (isOnline) "ONLINE" else "OFFLINE", isReachable = true) return NodeStatus(isOnline = isOnline, statusText = if (isOnline) "ONLINE" else "OFFLINE", isReachable = true)
} else { } else {
return NodeStatus(isOnline = false, statusText = "OFFLINE", isReachable = false) return NodeStatus(isOnline = false, statusText = "OFFLINE", isReachable = false)
@@ -93,6 +93,7 @@ import com.expapp.trigger.update.UpdateCheckResult
import com.expapp.trigger.update.UpdateManager import com.expapp.trigger.update.UpdateManager
import com.expapp.trigger.widget.ServerWidgetProvider import com.expapp.trigger.widget.ServerWidgetProvider
import com.expapp.trigger.worker.ActionTriggerWorker import com.expapp.trigger.worker.ActionTriggerWorker
import com.expapp.trigger.worker.AppUpdateWorker
import com.expapp.trigger.worker.ServerMonitorWorker import com.expapp.trigger.worker.ServerMonitorWorker
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive import kotlinx.coroutines.isActive
@@ -212,8 +213,14 @@ fun MainScreen(
showUpdateDialog = true showUpdateDialog = true
val newVer = result.info.versionName val newVer = result.info.versionName
if (appSettings.lastNotifiedUpdateVersion != newVer) { if (appSettings.lastNotifiedUpdateVersion != newVer) {
appSettings.lastNotifiedUpdateVersion = newVer val notified = com.expapp.trigger.worker.NotificationHelper.sendUpdateAvailableNotification(
com.expapp.trigger.worker.NotificationHelper.sendUpdateAvailableNotification(context, newVer) context = context,
newVersion = newVer,
releaseTitle = result.info.title
)
if (notified) {
appSettings.lastNotifiedUpdateVersion = newVer
}
} }
if (isManual) { if (isManual) {
Toast.makeText(context, "New update available: v${result.info.versionName}!", Toast.LENGTH_SHORT).show() Toast.makeText(context, "New update available: v${result.info.versionName}!", Toast.LENGTH_SHORT).show()
@@ -569,8 +576,10 @@ fun MainScreen(
appSettings.isBackgroundMonitoringEnabled = enabled appSettings.isBackgroundMonitoringEnabled = enabled
if (enabled) { if (enabled) {
ServerMonitorWorker.schedule(context) ServerMonitorWorker.schedule(context)
AppUpdateWorker.schedule(context)
} else { } else {
ServerMonitorWorker.cancel(context) ServerMonitorWorker.cancel(context)
AppUpdateWorker.cancel(context)
} }
}, },
isBiometricAvailable = BiometricHelper.isBiometricAvailable(context), isBiometricAvailable = BiometricHelper.isBiometricAvailable(context),
@@ -136,11 +136,12 @@ class ActionTriggerWorker(
triggerClient: TriggerClient, triggerClient: TriggerClient,
appSettings: AppSettings appSettings: AppSettings
) { ) {
val maxAttempts = 15 // Up to 60 seconds (15 attempts * 4s) val maxAttempts = 30 // Up to 60 seconds (30 attempts * 2s) for instant notification
var attempts = 0 var attempts = 0
var consecutiveTargetMatches = 0
// Brief delay for hardware/OS to begin reaction // Brief delay before first check to allow server to receive trigger
delay(4000L) delay(1500L)
while (attempts < maxAttempts) { while (attempts < maxAttempts) {
attempts++ attempts++
@@ -148,42 +149,54 @@ class ActionTriggerWorker(
// If phone network is unavailable, do not misinterpret as server going offline // If phone network is unavailable, do not misinterpret as server going offline
if (!status.isReachable) { if (!status.isReachable) {
delay(4000L) delay(2000L)
continue continue
} }
when (action) { when (action) {
TriggerAction.POWER_ON -> { TriggerAction.POWER_ON -> {
if (status.isOnline) { if (status.isOnline) {
appSettings.setLastStatus(device.id, true) consecutiveTargetMatches++
NotificationHelper.sendNotification( // Require 2 consecutive online confirmations (or 1 if status explicitly verified)
context = appContext, if (consecutiveTargetMatches >= 2 || status.statusText == "ONLINE") {
id = device.id.hashCode(), appSettings.setLastStatus(device.id, true)
title = "✅ Server Online", NotificationHelper.sendNotification(
message = "${device.name} is now online and reachable.", context = appContext,
isSuccess = true id = device.id.hashCode(),
) title = "✅ Server Online",
ServerWidgetProvider.updateAllWidgets(appContext) message = "${device.name} is now online and reachable.",
return isSuccess = true
)
ServerWidgetProvider.updateAllWidgets(appContext)
return
}
} else {
consecutiveTargetMatches = 0
} }
} }
TriggerAction.POWER_OFF -> { TriggerAction.POWER_OFF -> {
if (!status.isOnline) { if (!status.isOnline) {
appSettings.setLastStatus(device.id, false) consecutiveTargetMatches++
NotificationHelper.sendNotification( // Require 2 consecutive offline confirmations to completely eliminate false positives
context = appContext, if (consecutiveTargetMatches >= 2) {
id = device.id.hashCode(), appSettings.setLastStatus(device.id, false)
title = "⚠️ Server Offline", NotificationHelper.sendNotification(
message = "${device.name} has powered off or is offline.", context = appContext,
isSuccess = false id = device.id.hashCode(),
) title = "⚠️ Server Offline",
ServerWidgetProvider.updateAllWidgets(appContext) message = "${device.name} has powered off or is offline.",
return isSuccess = false
)
ServerWidgetProvider.updateAllWidgets(appContext)
return
}
} else {
consecutiveTargetMatches = 0
} }
} }
TriggerAction.REBOOT -> { TriggerAction.REBOOT -> {
// No notification for reboot per user instructions // No notification for reboot per user instructions
if (attempts >= 2 && status.isOnline) { if (attempts >= 4 && status.isOnline) {
appSettings.setLastStatus(device.id, true) appSettings.setLastStatus(device.id, true)
ServerWidgetProvider.updateAllWidgets(appContext) ServerWidgetProvider.updateAllWidgets(appContext)
return return
@@ -191,7 +204,7 @@ class ActionTriggerWorker(
} }
} }
delay(4000L) delay(2000L)
} }
} }
} }
@@ -0,0 +1,105 @@
package com.expapp.trigger.worker
import android.content.Context
import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import com.expapp.trigger.BuildConfig
import com.expapp.trigger.data.repository.AppSettings
import com.expapp.trigger.update.UpdateCheckResult
import com.expapp.trigger.update.UpdateManager
import java.util.concurrent.TimeUnit
/**
* Dedicated background worker that checks for new app updates independently of server devices.
* Ensures notifications are dispatched even if no servers are configured or if servers are offline.
*/
class AppUpdateWorker(
private val appContext: Context,
workerParams: WorkerParameters
) : CoroutineWorker(appContext, workerParams) {
companion object {
const val WORK_NAME = "app_update_periodic_check"
const val ONE_TIME_WORK_NAME = "app_update_one_time_check"
fun schedule(context: Context, repeatIntervalMinutes: Long = 15) {
NotificationHelper.createNotificationChannel(context)
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val workRequest = PeriodicWorkRequestBuilder<AppUpdateWorker>(
repeatIntervalMinutes,
TimeUnit.MINUTES
)
.setConstraints(constraints)
.build()
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
WORK_NAME,
ExistingPeriodicWorkPolicy.UPDATE,
workRequest
)
}
fun cancel(context: Context) {
WorkManager.getInstance(context).cancelUniqueWork(WORK_NAME)
}
fun runOnce(context: Context) {
NotificationHelper.createNotificationChannel(context)
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val oneTimeRequest = OneTimeWorkRequestBuilder<AppUpdateWorker>()
.setConstraints(constraints)
.build()
WorkManager.getInstance(context).enqueueUniqueWork(
ONE_TIME_WORK_NAME,
ExistingWorkPolicy.REPLACE,
oneTimeRequest
)
}
}
override suspend fun doWork(): Result {
val appSettings = AppSettings(appContext)
try {
val updateManager = UpdateManager(appContext)
val currentVersion = BuildConfig.VERSION_NAME
val result = updateManager.checkForUpdateSync(currentVersion)
if (result is UpdateCheckResult.UpdateAvailable) {
val newVer = result.info.versionName
val lastNotified = appSettings.lastNotifiedUpdateVersion
if (lastNotified != newVer) {
val notified = NotificationHelper.sendUpdateAvailableNotification(
context = appContext,
newVersion = newVer,
releaseTitle = result.info.title
)
if (notified) {
appSettings.lastNotifiedUpdateVersion = newVer
}
}
}
} catch (_: Exception) {
// Ignore failure; will retry next interval
}
return Result.success()
}
}
@@ -85,11 +85,20 @@ object NotificationHelper {
} }
} }
fun sendUpdateAvailableNotification(context: Context, newVersion: String): Boolean { fun sendUpdateAvailableNotification(
context: Context,
newVersion: String,
releaseTitle: String? = null
): Boolean {
val title = if (!releaseTitle.isNullOrBlank() && releaseTitle != "v$newVersion") {
"🚀 Update Available: $releaseTitle"
} else {
"🚀 Update Available: v$newVersion"
}
return sendNotification( return sendNotification(
context = context, context = context,
id = 8888, id = 8888,
title = "🚀 Update Available: v$newVersion", title = title,
message = "A new version (v$newVersion) of Device Trigger is ready to install. Tap to update!", message = "A new version (v$newVersion) of Device Trigger is ready to install. Tap to update!",
isSuccess = true, isSuccess = true,
extraAction = "open_update" extraAction = "open_update"
@@ -91,7 +91,7 @@ class ServerMonitorWorker(
for (device in devices) { for (device in devices) {
if (device.statusUrl.isBlank()) continue if (device.statusUrl.isBlank()) continue
val status = triggerClient.checkStatusSync(device) var status = triggerClient.checkStatusSync(device)
// If the endpoint could not be reached (e.g. phone has no internet / network failure), // If the endpoint could not be reached (e.g. phone has no internet / network failure),
// do NOT treat this as the server going offline. Maintain the last known state. // do NOT treat this as the server going offline. Maintain the last known state.
@@ -101,7 +101,20 @@ class ServerMonitorWorker(
val previousStatus = appSettings.getLastStatus(device.id) val previousStatus = appSettings.getLastStatus(device.id)
// Save new status // If a transition is detected (especially online -> offline or offline -> online),
// double-check with an immediate secondary request after 2 seconds to eliminate false positives
if (previousStatus != null && previousStatus != status.isOnline) {
kotlinx.coroutines.delay(2000L)
val verificationStatus = triggerClient.checkStatusSync(device)
if (verificationStatus.isReachable && verificationStatus.isOnline == status.isOnline) {
status = verificationStatus
} else {
// False positive or transient state; do not change status or trigger false alert
continue
}
}
// Save new verified status
appSettings.setLastStatus(device.id, status.isOnline) appSettings.setLastStatus(device.id, status.isOnline)
// Determine if notification is needed only when server actually transitions // Determine if notification is needed only when server actually transitions
@@ -129,8 +142,14 @@ class ServerMonitorWorker(
val newVer = result.info.versionName val newVer = result.info.versionName
val lastNotified = appSettings.lastNotifiedUpdateVersion val lastNotified = appSettings.lastNotifiedUpdateVersion
if (lastNotified != newVer) { if (lastNotified != newVer) {
appSettings.lastNotifiedUpdateVersion = newVer val notified = NotificationHelper.sendUpdateAvailableNotification(
NotificationHelper.sendUpdateAvailableNotification(appContext, newVer) context = appContext,
newVersion = newVer,
releaseTitle = result.info.title
)
if (notified) {
appSettings.lastNotifiedUpdateVersion = newVer
}
} }
} }
} catch (_: Exception) { } catch (_: Exception) {