Abrarul8541 commited on
Commit
ba77a6b
·
verified ·
1 Parent(s): 2da7fef

Service: start/stop helpers, safe start from foreground only

Browse files
app/src/main/java/io/github/abrarul/modularai/service/AgentService.kt CHANGED
@@ -26,9 +26,11 @@ class AgentService : Service() {
26
  .addAction(Notification.Action.Builder(null, "Stop", stop).build())
27
  .build()
28
  startForeground(1, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
29
- wake = getSystemService(PowerManager::class.java)
30
- .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "modularai:agent").apply { acquire(30 * 60 * 1000L) }
31
- return START_STICKY
 
 
32
  }
33
 
34
  override fun onDestroy() { wake?.takeIf { it.isHeld }?.release(); super.onDestroy() }
@@ -37,6 +39,13 @@ class AgentService : Service() {
37
  companion object {
38
  private const val CH = "agent"
39
  const val ACTION_STOP = "io.github.abrarul.modularai.STOP"
40
- fun start(ctx: Context) = ctx.startForegroundService(Intent(ctx, AgentService::class.java))
 
 
 
 
 
 
 
41
  }
42
  }
 
26
  .addAction(Notification.Action.Builder(null, "Stop", stop).build())
27
  .build()
28
  startForeground(1, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
29
+ if (wake?.isHeld != true) {
30
+ wake = getSystemService(PowerManager::class.java)
31
+ .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "modularai:agent").apply { acquire(2 * 60 * 60 * 1000L) }
32
+ }
33
+ return START_NOT_STICKY
34
  }
35
 
36
  override fun onDestroy() { wake?.takeIf { it.isHeld }?.release(); super.onDestroy() }
 
39
  companion object {
40
  private const val CH = "agent"
41
  const val ACTION_STOP = "io.github.abrarul.modularai.STOP"
42
+
43
+ /** Android only allows this while the app is visible; failures are ignored (the job still runs). */
44
+ fun start(ctx: Context) {
45
+ runCatching { ctx.startForegroundService(Intent(ctx, AgentService::class.java)) }
46
+ }
47
+ fun stop(ctx: Context) {
48
+ runCatching { ctx.stopService(Intent(ctx, AgentService::class.java)) }
49
+ }
50
  }
51
  }