feat: guaranteed background action execution & notifications via ActionTriggerWorker (v1.1.5)
Build & Release Android APK / Build & Publish Release APK (push) Canceled after 0s
Build & Release Android APK / Build & Publish Release APK (push) Canceled after 0s
This commit is contained in:
@@ -11,8 +11,8 @@ android {
|
||||
applicationId = "com.expapp.trigger"
|
||||
minSdk = 24
|
||||
targetSdk = 34
|
||||
versionCode = 8
|
||||
versionName = "1.1.4"
|
||||
versionCode = 9
|
||||
versionName = "1.1.5"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
vectorDrawables {
|
||||
|
||||
@@ -38,6 +38,7 @@ import com.expapp.trigger.ui.screens.MainScreen
|
||||
import com.expapp.trigger.ui.theme.DarkBackground
|
||||
import com.expapp.trigger.ui.theme.ExpAppTheme
|
||||
import com.expapp.trigger.widget.ServerWidgetProvider
|
||||
import com.expapp.trigger.worker.ActionTriggerWorker
|
||||
import com.expapp.trigger.worker.NotificationHelper
|
||||
import com.expapp.trigger.worker.ServerMonitorWorker
|
||||
|
||||
@@ -265,27 +266,7 @@ class MainActivity : FragmentActivity() {
|
||||
val onAuthorized = {
|
||||
vibrateFeedback(true)
|
||||
Toast.makeText(this, "Sending $actionName signal to ${device.name}...", Toast.LENGTH_SHORT).show()
|
||||
triggerClient.sendTrigger(device, action) { response ->
|
||||
val msg = if (response.isSuccess) {
|
||||
"$actionName signal sent successfully"
|
||||
} else {
|
||||
"Failed: ${response.message.take(50)}"
|
||||
}
|
||||
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
|
||||
historyRepository.addLog(
|
||||
TriggerLog(
|
||||
deviceId = device.id,
|
||||
deviceName = device.name,
|
||||
node = device.node,
|
||||
action = action,
|
||||
isSuccess = response.isSuccess,
|
||||
statusCode = response.statusCode,
|
||||
message = response.message,
|
||||
source = source
|
||||
)
|
||||
)
|
||||
ServerWidgetProvider.updateAllWidgets(this)
|
||||
}
|
||||
ActionTriggerWorker.enqueue(this, device.id, action, source)
|
||||
}
|
||||
|
||||
if (appSettings.isBiometricEnabled && BiometricHelper.isBiometricAvailable(this)) {
|
||||
|
||||
@@ -92,6 +92,7 @@ import com.expapp.trigger.update.ReleaseInfo
|
||||
import com.expapp.trigger.update.UpdateCheckResult
|
||||
import com.expapp.trigger.update.UpdateManager
|
||||
import com.expapp.trigger.widget.ServerWidgetProvider
|
||||
import com.expapp.trigger.worker.ActionTriggerWorker
|
||||
import com.expapp.trigger.worker.ServerMonitorWorker
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.isActive
|
||||
@@ -283,45 +284,22 @@ fun MainScreen(
|
||||
val performDispatch = {
|
||||
loadingStates[device.id] = true
|
||||
statusStates.remove(device.id)
|
||||
triggerClient.sendTrigger(device, action) { response ->
|
||||
loadingStates[device.id] = false
|
||||
val msg = if (response.isSuccess) {
|
||||
when (action) {
|
||||
TriggerAction.POWER_ON -> "Power on signal sent"
|
||||
TriggerAction.POWER_OFF -> "Shutdown signal sent"
|
||||
TriggerAction.REBOOT -> "Restart signal sent"
|
||||
}
|
||||
} else {
|
||||
val raw = response.message.trim()
|
||||
val clean = if (raw.startsWith("<")) "Request failed (HTTP ${response.statusCode})" else raw.take(60)
|
||||
"Failed — $clean"
|
||||
}
|
||||
statusStates[device.id] = msg to response.isSuccess
|
||||
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
|
||||
Toast.makeText(context, "Sending $actionTitle signal to ${device.name}...", Toast.LENGTH_SHORT).show()
|
||||
|
||||
// Save to history log
|
||||
historyRepository.addLog(
|
||||
TriggerLog(
|
||||
deviceId = device.id,
|
||||
deviceName = device.name,
|
||||
node = device.node,
|
||||
action = action,
|
||||
isSuccess = response.isSuccess,
|
||||
statusCode = response.statusCode,
|
||||
message = msg,
|
||||
source = "App"
|
||||
)
|
||||
)
|
||||
// Enqueue guaranteed background worker: executes HTTP request, sends notifications, updates widgets & monitors transition
|
||||
ActionTriggerWorker.enqueue(context, device.id, action, "App")
|
||||
|
||||
// In foreground, refresh UI smoothly after short intervals if user stays in the app
|
||||
coroutineScope.launch {
|
||||
delay(2000)
|
||||
refreshStatus(device, showIndicator = true)
|
||||
historyLogs = historyRepository.getLogs()
|
||||
|
||||
// Update home screen widgets
|
||||
ServerWidgetProvider.updateAllWidgets(context)
|
||||
|
||||
coroutineScope.launch {
|
||||
delay(1500); refreshStatus(device, showIndicator = true)
|
||||
delay(4000); refreshStatus(device)
|
||||
delay(5000); refreshStatus(device)
|
||||
}
|
||||
loadingStates[device.id] = false
|
||||
delay(3000)
|
||||
refreshStatus(device, showIndicator = false)
|
||||
historyLogs = historyRepository.getLogs()
|
||||
delay(4000)
|
||||
refreshStatus(device, showIndicator = false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ import com.expapp.trigger.data.repository.TriggerHistoryRepository
|
||||
import com.expapp.trigger.network.NodeStatus
|
||||
import com.expapp.trigger.network.TriggerAction
|
||||
import com.expapp.trigger.network.TriggerClient
|
||||
import com.expapp.trigger.worker.ActionTriggerWorker
|
||||
import java.util.concurrent.Executors
|
||||
|
||||
class ServerWidgetProvider : AppWidgetProvider() {
|
||||
@@ -95,41 +96,9 @@ class ServerWidgetProvider : AppWidgetProvider() {
|
||||
}
|
||||
context.startActivity(launchIntent)
|
||||
} else {
|
||||
// Biometric disabled: execute directly in background
|
||||
executor.execute {
|
||||
val repository = DeviceRepository(SharedPrefsStorage(context))
|
||||
val device = repository.getDevices().find { it.id == deviceId } ?: return@execute
|
||||
val client = TriggerClient()
|
||||
|
||||
val response = client.sendTriggerSync(device, action)
|
||||
val historyRepo = TriggerHistoryRepository(context)
|
||||
historyRepo.addLog(
|
||||
TriggerLog(
|
||||
deviceId = device.id,
|
||||
deviceName = device.name,
|
||||
node = device.node,
|
||||
action = action,
|
||||
isSuccess = response.isSuccess,
|
||||
statusCode = response.statusCode,
|
||||
message = response.message,
|
||||
source = "Widget"
|
||||
)
|
||||
)
|
||||
|
||||
mainHandler.post {
|
||||
val msg = if (response.isSuccess) {
|
||||
when (action) {
|
||||
TriggerAction.POWER_ON -> "Power on sent to ${device.name}"
|
||||
TriggerAction.REBOOT -> "Restart sent to ${device.name}"
|
||||
TriggerAction.POWER_OFF -> "Shutdown sent to ${device.name}"
|
||||
}
|
||||
} else {
|
||||
"Failed: ${response.message.take(40)}"
|
||||
}
|
||||
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
|
||||
updateAllWidgets(context)
|
||||
}
|
||||
}
|
||||
// Biometric disabled: execute via guaranteed background worker
|
||||
Toast.makeText(context, "Sending ${action.name} signal...", Toast.LENGTH_SHORT).show()
|
||||
ActionTriggerWorker.enqueue(context, deviceId, action, "Widget")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
package com.expapp.trigger.worker
|
||||
|
||||
import android.content.Context
|
||||
import androidx.work.Constraints
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.Data
|
||||
import androidx.work.ExistingWorkPolicy
|
||||
import androidx.work.NetworkType
|
||||
import androidx.work.OneTimeWorkRequestBuilder
|
||||
import androidx.work.WorkManager
|
||||
import androidx.work.WorkerParameters
|
||||
import com.expapp.trigger.data.model.DeviceConfig
|
||||
import com.expapp.trigger.data.model.TriggerLog
|
||||
import com.expapp.trigger.data.repository.AppSettings
|
||||
import com.expapp.trigger.data.repository.DeviceRepository
|
||||
import com.expapp.trigger.data.repository.SharedPrefsStorage
|
||||
import com.expapp.trigger.data.repository.TriggerHistoryRepository
|
||||
import com.expapp.trigger.network.TriggerAction
|
||||
import com.expapp.trigger.network.TriggerClient
|
||||
import com.expapp.trigger.widget.ServerWidgetProvider
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
class ActionTriggerWorker(
|
||||
private val appContext: Context,
|
||||
workerParams: WorkerParameters
|
||||
) : CoroutineWorker(appContext, workerParams) {
|
||||
|
||||
companion object {
|
||||
const val KEY_DEVICE_ID = "device_id"
|
||||
const val KEY_ACTION = "action"
|
||||
const val KEY_SOURCE = "source"
|
||||
|
||||
/**
|
||||
* Enqueues guaranteed background execution of a server power action.
|
||||
* Runs even if the user immediately closes the app, locks phone, or clears recents.
|
||||
*/
|
||||
fun enqueue(
|
||||
context: Context,
|
||||
deviceId: String,
|
||||
action: TriggerAction,
|
||||
source: String = "App"
|
||||
) {
|
||||
NotificationHelper.createNotificationChannel(context)
|
||||
|
||||
val inputData = Data.Builder()
|
||||
.putString(KEY_DEVICE_ID, deviceId)
|
||||
.putString(KEY_ACTION, action.name)
|
||||
.putString(KEY_SOURCE, source)
|
||||
.build()
|
||||
|
||||
val constraints = Constraints.Builder()
|
||||
.setRequiredNetworkType(NetworkType.CONNECTED)
|
||||
.build()
|
||||
|
||||
val workRequest = OneTimeWorkRequestBuilder<ActionTriggerWorker>()
|
||||
.setInputData(inputData)
|
||||
.setConstraints(constraints)
|
||||
.build()
|
||||
|
||||
WorkManager.getInstance(context).enqueueUniqueWork(
|
||||
"action_trigger_${deviceId}",
|
||||
ExistingWorkPolicy.REPLACE,
|
||||
workRequest
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun doWork(): Result {
|
||||
val deviceId = inputData.getString(KEY_DEVICE_ID) ?: return Result.failure()
|
||||
val actionName = inputData.getString(KEY_ACTION) ?: return Result.failure()
|
||||
val source = inputData.getString(KEY_SOURCE) ?: "App"
|
||||
|
||||
val action = try {
|
||||
TriggerAction.valueOf(actionName)
|
||||
} catch (e: Exception) {
|
||||
return Result.failure()
|
||||
}
|
||||
|
||||
val repository = DeviceRepository(SharedPrefsStorage(appContext))
|
||||
val device = repository.getDevices().find { it.id == deviceId } ?: return Result.failure()
|
||||
|
||||
val actionTitle = when (action) {
|
||||
TriggerAction.POWER_ON -> "Power On"
|
||||
TriggerAction.REBOOT -> "Reboot"
|
||||
TriggerAction.POWER_OFF -> "Shutdown"
|
||||
}
|
||||
|
||||
val triggerClient = TriggerClient()
|
||||
val historyRepo = TriggerHistoryRepository(appContext)
|
||||
val appSettings = AppSettings(appContext)
|
||||
|
||||
// 1. Execute the HTTP trigger to the server
|
||||
val response = triggerClient.sendTriggerSync(device, action)
|
||||
|
||||
// 2. Post notification immediately confirming the signal was sent (or failed)
|
||||
val signalMsg = if (response.isSuccess) {
|
||||
when (action) {
|
||||
TriggerAction.POWER_ON -> "Power on signal sent successfully to ${device.name}"
|
||||
TriggerAction.POWER_OFF -> "Shutdown signal sent to ${device.name}"
|
||||
TriggerAction.REBOOT -> "Reboot signal sent to ${device.name}"
|
||||
}
|
||||
} else {
|
||||
val raw = response.message.trim()
|
||||
val clean = if (raw.startsWith("<")) "HTTP ${response.statusCode}" else raw.take(60)
|
||||
"Failed to send $actionTitle: $clean"
|
||||
}
|
||||
|
||||
val actionIcon = when (action) {
|
||||
TriggerAction.POWER_ON -> "⚡"
|
||||
TriggerAction.POWER_OFF -> "🛑"
|
||||
TriggerAction.REBOOT -> "🔄"
|
||||
}
|
||||
|
||||
val notifTitle = if (response.isSuccess) {
|
||||
"$actionIcon $actionTitle: ${device.name}"
|
||||
} else {
|
||||
"❌ $actionTitle Failed: ${device.name}"
|
||||
}
|
||||
|
||||
// Send system notification to drawer
|
||||
NotificationHelper.sendNotification(
|
||||
context = appContext,
|
||||
id = (device.id.hashCode() * 31) + action.ordinal,
|
||||
title = notifTitle,
|
||||
message = signalMsg,
|
||||
isSuccess = response.isSuccess
|
||||
)
|
||||
|
||||
// 3. Save to history log
|
||||
historyRepo.addLog(
|
||||
TriggerLog(
|
||||
deviceId = device.id,
|
||||
deviceName = device.name,
|
||||
node = device.node,
|
||||
action = action,
|
||||
isSuccess = response.isSuccess,
|
||||
statusCode = response.statusCode,
|
||||
message = signalMsg,
|
||||
source = source
|
||||
)
|
||||
)
|
||||
|
||||
// 4. Update home screen widgets
|
||||
ServerWidgetProvider.updateAllWidgets(appContext)
|
||||
|
||||
// 5. If trigger succeeded and device has a status endpoint, actively poll until state changes!
|
||||
if (response.isSuccess && device.statusUrl.isNotBlank()) {
|
||||
pollForTransition(device, action, triggerClient, appSettings)
|
||||
}
|
||||
|
||||
return Result.success()
|
||||
}
|
||||
|
||||
private suspend fun pollForTransition(
|
||||
device: DeviceConfig,
|
||||
action: TriggerAction,
|
||||
triggerClient: TriggerClient,
|
||||
appSettings: AppSettings
|
||||
) {
|
||||
val maxAttempts = 15 // Up to 60 seconds (15 attempts * 4s)
|
||||
var attempts = 0
|
||||
|
||||
// Brief delay for hardware/OS to begin reaction
|
||||
delay(4000L)
|
||||
|
||||
while (attempts < maxAttempts) {
|
||||
attempts++
|
||||
val status = triggerClient.checkStatusSync(device)
|
||||
|
||||
when (action) {
|
||||
TriggerAction.POWER_ON -> {
|
||||
if (status.isOnline) {
|
||||
appSettings.setLastStatus(device.id, true)
|
||||
NotificationHelper.sendNotification(
|
||||
context = appContext,
|
||||
id = device.id.hashCode(),
|
||||
title = "✅ Server Online: ${device.name}",
|
||||
message = "${device.name} is now online and reachable!",
|
||||
isSuccess = true
|
||||
)
|
||||
ServerWidgetProvider.updateAllWidgets(appContext)
|
||||
return
|
||||
}
|
||||
}
|
||||
TriggerAction.POWER_OFF -> {
|
||||
if (!status.isOnline) {
|
||||
appSettings.setLastStatus(device.id, false)
|
||||
NotificationHelper.sendNotification(
|
||||
context = appContext,
|
||||
id = device.id.hashCode(),
|
||||
title = "🛑 Server Offline: ${device.name}",
|
||||
message = "${device.name} has shut down and is now offline.",
|
||||
isSuccess = false
|
||||
)
|
||||
ServerWidgetProvider.updateAllWidgets(appContext)
|
||||
return
|
||||
}
|
||||
}
|
||||
TriggerAction.REBOOT -> {
|
||||
if (attempts >= 2 && status.isOnline) {
|
||||
appSettings.setLastStatus(device.id, true)
|
||||
NotificationHelper.sendNotification(
|
||||
context = appContext,
|
||||
id = device.id.hashCode(),
|
||||
title = "✅ Reboot Complete: ${device.name}",
|
||||
message = "${device.name} successfully rebooted and is back online!",
|
||||
isSuccess = true
|
||||
)
|
||||
ServerWidgetProvider.updateAllWidgets(appContext)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
delay(4000L)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user