2 years ago
#43709

anta40
WorkRequest is not executed for handling nats.io notification on Android
I'm tinkering with nats.io as an alternative to Firebase Cloud Messaging
Here's the MainActivity:
mport android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import androidx.work.ExistingWorkPolicy
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
class MainActivity : AppCompatActivity() {
lateinit var btnStart: Button
lateinit var btnStop: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btnStart = findViewById<Button>(R.id.btnStartService)
btnStop = findViewById<Button>(R.id.btnStopService)
btnStart.setOnClickListener {
Log.d("ENDLESS_SERVICE","START THE FOREGROUND SERVICE ON DEMAND")
actionOnService(Actions.START_SERVICE)
WorkManager.getInstance(this)
.beginUniqueWork("MyBackgroundWorker", ExistingWorkPolicy.APPEND_OR_REPLACE,
OneTimeWorkRequest.from(MyBackgroundWorker::class.java)).enqueue().state
.observe(this) { state ->
Log.d("NATSDemo", "MyBackgroundWorker: $state")
}
}
btnStop.setOnClickListener {
Log.d("ENDLESS_SERVICE","START THE FOREGROUND SERVICE ON DEMAND")
actionOnService(Actions.STOP_SERVICE)
}
}
private fun actionOnService(action: Actions) {
if (getServiceState(this) == ServiceState.SERVICE_STOPPED && action == Actions.STOP_SERVICE) return
Intent(this, EndlessService::class.java).also {
it.action = action.name
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Log.d("ENDLESS_SERVICE","Starting the service in >=26 Mode")
startForegroundService(it)
return
}
Log.d("ENDLESS_SERVICE", "Starting the service in < 26 Mode")
startService(it)
}
}
}
If you take a look at the whole code, you'll notice the NATS connection is initiated each 3 minutes. I send messages using nats-cli, and interestingly, all the notifications appear in the Android notification tray have the title "NATS Demo" (from EndlessService.kt), but not even one from MyBackgroundWorker.kt, which has the title "Message from NATS". So MyBackgroundWorker is not executed at all. Why?
BTW, I found this on logcat, probably could be a useful hint:
2022-01-13 01:58:13.926 19560-19592/com.anta40.app.natsservicedemo I/WM-WorkerWrapper: Worker result SUCCESS for Work [ id=18c9ba36-a578-4957-b7f6-9205ef6183c9, tags={ com.anta40.app.natsservicedemo.MyBackgroundWorker } ]
2022-01-13 01:58:13.927 19560-19560/com.anta40.app.natsservicedemo I/WM-SystemFgDispatcher: Started foreground service Intent { act=ACTION_START_FOREGROUND cmp=com.anta40.app.natsservicedemo/androidx.work.impl.foreground.SystemForegroundService (has extras) }
2022-01-13 01:58:13.941 19560-19560/com.anta40.app.natsservicedemo I/WM-SystemFgDispatcher: Stopping foreground service
android
background-process
nats.io
0 Answers
Your Answer