Compare commits

..
3 Commits
Author SHA1 Message Date
Vaishno Singh 5c66f6c4dc fix(widget): fix 'Failed to load widget' by replacing View with FrameLayout, removing theme attrs & using PNG drawables (v1.2.3)
Build & Release Android APK / Build & Publish Release APK (push) Failing after 1m28s
2026-11-19 21:52:09 +05:30
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
13 changed files with 328 additions and 141 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 = 17
versionName = "1.2.0" versionName = "1.2.3"
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),
@@ -57,22 +57,34 @@ class ServerWidgetProvider : AppWidgetProvider() {
appWidgetManager: AppWidgetManager, appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray appWidgetIds: IntArray
) { ) {
val repository = DeviceRepository(SharedPrefsStorage(context)) try {
val devices = repository.getDevices() val repository = DeviceRepository(SharedPrefsStorage(context))
val devices = repository.getDevices()
for (appWidgetId in appWidgetIds) { for (appWidgetId in appWidgetIds) {
val device = devices.firstOrNull() val device = devices.firstOrNull()
renderWidget(context, appWidgetManager, appWidgetId, device, null) renderWidget(context, appWidgetManager, appWidgetId, device, null)
// If device exists, fetch live status asynchronously // If device exists, fetch live status asynchronously
if (device != null && device.statusUrl.isNotBlank()) { if (device != null && device.statusUrl.isNotBlank()) {
executor.execute { executor.execute {
val status = TriggerClient().checkStatusSync(device) try {
mainHandler.post { val status = TriggerClient().checkStatusSync(device)
renderWidget(context, appWidgetManager, appWidgetId, device, status) mainHandler.post {
try {
renderWidget(context, appWidgetManager, appWidgetId, device, status)
} catch (e: Exception) {
e.printStackTrace()
}
}
} catch (e: Exception) {
e.printStackTrace()
}
} }
} }
} }
} catch (e: Exception) {
e.printStackTrace()
} }
} }
@@ -131,92 +143,96 @@ class ServerWidgetProvider : AppWidgetProvider() {
status: NodeStatus?, status: NodeStatus?,
footerOverride: String? = null footerOverride: String? = null
) { ) {
val views = RemoteViews(context.packageName, R.layout.widget_server_control) try {
val views = RemoteViews(context.packageName, R.layout.widget_server_control)
if (device == null) { if (device == null) {
views.setTextViewText(R.id.widget_device_name, "No Device") views.setTextViewText(R.id.widget_device_name, "No Device")
views.setTextViewText(R.id.widget_node_name, "Configure in app") views.setTextViewText(R.id.widget_node_name, "Configure in app")
views.setTextViewText(R.id.widget_status_text, "OFFLINE") views.setTextViewText(R.id.widget_status_text, "OFFLINE")
views.setImageViewResource(R.id.widget_status_dot, R.drawable.widget_dot_gray) views.setImageViewResource(R.id.widget_status_dot, R.drawable.widget_dot_gray)
views.setTextViewText(R.id.widget_footer_text, "Open app to add server") views.setTextViewText(R.id.widget_footer_text, "Open app to add server")
val appIntent = Intent(context, MainActivity::class.java) val appIntent = Intent(context, MainActivity::class.java)
val pendingApp = PendingIntent.getActivity( val pendingApp = PendingIntent.getActivity(
context, 0, appIntent, context, 0, appIntent,
PendingIntent.FLAG_UPDATE_CURRENT or (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0)
)
views.setOnClickPendingIntent(R.id.widget_header_clickable, pendingApp)
views.setOnClickPendingIntent(R.id.widget_root, pendingApp)
appWidgetManager.updateAppWidget(appWidgetId, views)
return
}
views.setTextViewText(R.id.widget_device_name, device.name)
views.setTextViewText(R.id.widget_node_name, device.node)
// Status display
if (status == null) {
views.setTextViewText(R.id.widget_status_text, "SYNCING")
views.setTextColor(R.id.widget_status_text, 0xFF71717A.toInt())
views.setImageViewResource(R.id.widget_status_dot, R.drawable.widget_dot_gray)
} else if (status.isOnline) {
views.setTextViewText(R.id.widget_status_text, "ONLINE")
views.setTextColor(R.id.widget_status_text, 0xFF22C55E.toInt())
views.setImageViewResource(R.id.widget_status_dot, R.drawable.widget_dot_green)
} else {
views.setTextViewText(R.id.widget_status_text, "OFFLINE")
views.setTextColor(R.id.widget_status_text, 0xFFEF4444.toInt())
views.setImageViewResource(R.id.widget_status_dot, R.drawable.widget_dot_red)
}
views.setTextViewText(
R.id.widget_footer_text,
footerOverride ?: (if (status?.uptime != null) "Up: ${status.uptime}" else "Tap header to open • Tap button to trigger")
)
// Header click -> Open app
val openAppIntent = Intent(context, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
}
val pendingOpenApp = PendingIntent.getActivity(
context,
appWidgetId * 10,
openAppIntent,
PendingIntent.FLAG_UPDATE_CURRENT or (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0) PendingIntent.FLAG_UPDATE_CURRENT or (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0)
) )
views.setOnClickPendingIntent(R.id.widget_header_clickable, pendingApp) views.setOnClickPendingIntent(R.id.widget_header_clickable, pendingOpenApp)
views.setOnClickPendingIntent(R.id.widget_root, pendingApp)
// Refresh click
val refreshIntent = Intent(context, ServerWidgetProvider::class.java).apply {
action = ACTION_REFRESH
}
val pendingRefresh = PendingIntent.getBroadcast(
context,
appWidgetId * 10 + 1,
refreshIntent,
PendingIntent.FLAG_UPDATE_CURRENT or (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0)
)
views.setOnClickPendingIntent(R.id.widget_btn_refresh, pendingRefresh)
// Power On click
views.setOnClickPendingIntent(
R.id.widget_btn_power_on,
createTriggerPendingIntent(context, appWidgetId * 10 + 2, device.id, TriggerAction.POWER_ON)
)
// Reboot click
views.setOnClickPendingIntent(
R.id.widget_btn_reboot,
createTriggerPendingIntent(context, appWidgetId * 10 + 3, device.id, TriggerAction.REBOOT)
)
// Power Off click
views.setOnClickPendingIntent(
R.id.widget_btn_power_off,
createTriggerPendingIntent(context, appWidgetId * 10 + 4, device.id, TriggerAction.POWER_OFF)
)
appWidgetManager.updateAppWidget(appWidgetId, views) appWidgetManager.updateAppWidget(appWidgetId, views)
return } catch (e: Exception) {
e.printStackTrace()
} }
views.setTextViewText(R.id.widget_device_name, device.name)
views.setTextViewText(R.id.widget_node_name, device.node)
// Status display
if (status == null) {
views.setTextViewText(R.id.widget_status_text, "SYNCING")
views.setTextColor(R.id.widget_status_text, 0xFF71717A.toInt())
views.setImageViewResource(R.id.widget_status_dot, R.drawable.widget_dot_gray)
} else if (status.isOnline) {
views.setTextViewText(R.id.widget_status_text, "ONLINE")
views.setTextColor(R.id.widget_status_text, 0xFF22C55E.toInt())
views.setImageViewResource(R.id.widget_status_dot, R.drawable.widget_dot_green)
} else {
views.setTextViewText(R.id.widget_status_text, "OFFLINE")
views.setTextColor(R.id.widget_status_text, 0xFFEF4444.toInt())
views.setImageViewResource(R.id.widget_status_dot, R.drawable.widget_dot_red)
}
views.setTextViewText(
R.id.widget_footer_text,
footerOverride ?: (if (status?.uptime != null) "Up: ${status.uptime}" else "Tap header to open • Tap button to trigger")
)
// Header click -> Open app
val openAppIntent = Intent(context, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
}
val pendingOpenApp = PendingIntent.getActivity(
context,
appWidgetId * 10,
openAppIntent,
PendingIntent.FLAG_UPDATE_CURRENT or (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0)
)
views.setOnClickPendingIntent(R.id.widget_header_clickable, pendingOpenApp)
// Refresh click
val refreshIntent = Intent(context, ServerWidgetProvider::class.java).apply {
action = ACTION_REFRESH
}
val pendingRefresh = PendingIntent.getBroadcast(
context,
appWidgetId * 10 + 1,
refreshIntent,
PendingIntent.FLAG_UPDATE_CURRENT or (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0)
)
views.setOnClickPendingIntent(R.id.widget_btn_refresh, pendingRefresh)
// Power On click
views.setOnClickPendingIntent(
R.id.widget_btn_power_on,
createTriggerPendingIntent(context, appWidgetId * 10 + 2, device.id, TriggerAction.POWER_ON)
)
// Reboot click
views.setOnClickPendingIntent(
R.id.widget_btn_reboot,
createTriggerPendingIntent(context, appWidgetId * 10 + 3, device.id, TriggerAction.REBOOT)
)
// Power Off click
views.setOnClickPendingIntent(
R.id.widget_btn_power_off,
createTriggerPendingIntent(context, appWidgetId * 10 + 4, device.id, TriggerAction.POWER_OFF)
)
appWidgetManager.updateAppWidget(appWidgetId, views)
} }
private fun createTriggerPendingIntent( private fun createTriggerPendingIntent(
@@ -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) {
Binary file not shown.

After

Width:  |  Height:  |  Size: 324 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 314 B

@@ -17,7 +17,7 @@
<ImageView <ImageView
android:layout_width="18dp" android:layout_width="18dp"
android:layout_height="18dp" android:layout_height="18dp"
android:src="@drawable/ic_terminal" android:src="@drawable/widget_ic_terminal"
android:contentDescription="Server" /> android:contentDescription="Server" />
<LinearLayout <LinearLayout
@@ -82,14 +82,13 @@
android:id="@+id/widget_btn_refresh" android:id="@+id/widget_btn_refresh"
android:layout_width="26dp" android:layout_width="26dp"
android:layout_height="26dp" android:layout_height="26dp"
android:background="?android:attr/selectableItemBackgroundBorderless"
android:contentDescription="Refresh" android:contentDescription="Refresh"
android:padding="3dp" android:padding="3dp"
android:src="@drawable/ic_refresh" /> android:src="@drawable/widget_ic_refresh" />
</LinearLayout> </LinearLayout>
<!-- Spacer / Divider --> <!-- Spacer / Divider (FrameLayout is explicitly whitelisted in RemoteViews) -->
<View <FrameLayout
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="1dp" android:layout_height="1dp"
android:layout_marginTop="8dp" android:layout_marginTop="8dp"
+6 -2
View File
@@ -1,7 +1,11 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="250dp" android:minWidth="220dp"
android:minHeight="100dp" android:minHeight="90dp"
android:targetCellWidth="3"
android:targetCellHeight="2"
android:minResizeWidth="180dp"
android:minResizeHeight="70dp"
android:updatePeriodMillis="1800000" android:updatePeriodMillis="1800000"
android:initialLayout="@layout/widget_server_control" android:initialLayout="@layout/widget_server_control"
android:resizeMode="horizontal|vertical" android:resizeMode="horizontal|vertical"