My WorkManager isn't running in foreground or background - android

This is the code I am using to setup the work task in my main activity:
val apiFetchBuilder = PeriodicWorkRequestBuilder<APIWorker>(timeValue, TimeUnit.MINUTES) // timeValue = 1 for testing
val apiFetchWorker = apiFetchBuilder.build()
val instance = WorkManager.getInstance(this)
instance.enqueueUniquePeriodicWork(Constants.background_work, ExistingPeriodicWorkPolicy.KEEP, apiFetchWorker)
and then my work manager is setup as follows:
class APIWorker(context: Context, workerParams: WorkerParameters): Worker(context, workerParams){
override fun doWork(): Result {
Log.d("WorkManager", "doWork: ")
//Do API Work here
return Result.success()
}
The logcat isn't registering this call at all no matter how long I wait or how many times I open the main activity to enqueue the work manager

Related

How to access other custom method outside work manager?

I am working on app in which first i have to start the process and then update the value so how to access other methods of custom method o workmanager thanks
class SmsWorkManager(val context : Context, workerParameters:WorkerParameters) : CoroutineWorker(context ,workerParameters) {
override suspend fun doWork(): Result {
println("do some task ")}
fun updateMethod(){
println("how to access this method")}
}
// class Instannce for work maanager
val workManager = WorkManager.getInstance(this )
// val oneTimeRequest =OneTimeWorkRequest.Builder(SmsWorkManager::class.java)
workManager.enqueue(oneTimeRequest.build())
You need to return a Result after work completion & you can simply use the updateMethod() inside your `doWork() like below:
class SmsWorkManager(val context: Context, params: WorkerParameters) :
CoroutineWorker(context, params) {
override suspend fun doWork(): Result {
println("do some task ")
updateMethod()
return Result.success()
}
fun updateMethod(){
println("how to access this method")
}
}
Also, if you are not doing any IO task then you should use a Worker instead of a CoroutineWorker.

How to get the remaining time after which worker will do work?

I schedule one time work in 100 minutes:
val request = OneTimeWorkRequestBuilder<MyWorker().setInitialDelay(100, TimeUnit.MINUTES).build()
WorkManager.getInstance(context).enqueueUniqueWork(
"MY_WORKER_NAME",
ExistingWorkPolicy.REPLACE,
request
)
class MyWorker(context: Context, workerParameters: WorkerParameters) : CoroutineWorker(
context, workerParameters) {
override suspend fun doWork(): Result {
return Result.success()
}
How can I get the remaining time, before doWork() is executed?
For example, I need to know it immediately after I reboot my Android device

How can I handle finished work OneTimeWorkRequest?

Hi everyone. As the title suggests, I need to take the time when WorkManager finishes its work (every 60 seconds) to perform other operations. At the moment I know that I can't use it for jobs less than 15 minutes, but by trying some different way I can get around the problem. But the fact remains that I need to figure out when the OneTimeWorkRequest command timer ends. What do you suggest to me?
Here my code:
MainActivity:
class MAinActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setPeriodicallySendingLogs()
}
private fun setPeriodicallySendingLogs() {
val workManager = WorkManager.getInstance(this)
val sendingLog = PeriodicWorkRequestBuilder<SendLogWorker>(15, TimeUnit.MINUTES)
.build()
workManager.enqueue(sendingLog)
workManager.getWorkInfoByIdLiveData(sendingLog.id)
.observe(this, Observer { workInfo ->
Log.d("WM", " info${workInfo.state.name}")
})
}
}
Worker:
class SendLogWorker(private val context: Context, userParameters: WorkerParameters) :
Worker(context, userParameters) {
override fun doWork(): Result {
val mywork = OneTimeWorkRequest.Builder(SendLogWorker::class.java)
.setInitialDelay(1, TimeUnit.MINUTES)
.build()
WorkManager.getInstance(context).enqueue(mywork)
return Result.success()
}
}
workManager.getWorkInfoByIdLiveData(syncWorker.id)
.observe(getViewLifecycleOwner(), workInfo -> {
if (workInfo.getState() != null &&
workInfo.getState() == WorkInfo.State.SUCCEEDED) {
Snackbar.make(requireView(),
R.string.work_completed, Snackbar.LENGTH_SHORT)
.show();
}
});
https://developer.android.com/topic/libraries/architecture/workmanager/how-to/managing-work

Android Worker doWork() runs into for-loop

I see from Server side that Android calls multiple /test API requests - looks like never-ending for loop.
This API is defined only in TestWorker class:
class TestWorker(
context: Context,
workerParams: WorkerParameters
) : Worker(context, workerParams) {
override fun doWork(): Result {
callApiRequest()
return Result.success()
}
private fun callApiRequest() {
XUseCase.execute()
.backgroundToMainThread()
.subscribe(
{ ->
..
},
{
..
}
)
}
companion object {
const val REPEAT_INTERVAL_IN_HOURS = 3L
}
}
private fun initTestWorker() {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val workerRequest = PeriodicWorkRequestBuilder<TestWorker>(TestWorker.REPEAT_INTERVAL_IN_HOURS, TimeUnit.HOURS)
.setConstraints(constraints)
.build()
WorkManager
.getInstance(this)
.enqueueUniquePeriodicWork("", ExistingPeriodicWorkPolicy.KEEP, workerRequest)
}
initTestWorker() gets called in MyApp onCreate() method. I'm not sure how, but maybe someone has experienced similar behaviour, from the front end I can not reproduce the issue. Any loop experiences using Worker?

Coroutine Worker gets killed after kill the app

Lets say that i have an activity that starts a worker. inside the worker i do a pseudo suspend proccess and then i print out a result from the database. Here is the code
The activity which starts the worker is
class SplashActivity: BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
val oneTimeRequest = OneTimeWorkRequest.Builder(MyWorker::class.java).setInputData(Data.Builder().apply {
putInt("data", 1)
}.build()).addTag("worktag").build()
WorkManager.getInstance(applicationContext).enqueue(oneTimeRequest)
}
}
The worker is the below
class MyWorker #AssistedInject constructor(
#Assisted private val appContext: Context,
#Assisted private val params: WorkerParameters,
private val serverRepository: ServerRepository
) : CoroutineWorker(appContext, params) {
override suspend fun doWork(): Result {
GlobalScope.launch {
for (i in 0..10) {
println("$i")
delay(1000)
}
val servers = serverRepository.getServers()
runOnUiThread {
Toast.makeText(appContext, "${servers.firstOrNull()?.serverAddress}", Toast.LENGTH_SHORT).show()
}
}
return Result.success()
}
}
So the result is that i see in the logcat the system.out with 1,2,3... and then i see a toast messages.
However, when i totally kill the app from the recent while the counter still counts, i never see the toast message.
Why is this happening since i have a GlobalScope coroutine?
And what is the right way to do this??
I was trying to achieve a similar goal. I managed my work by using ForegroundService.
You can find more here
https://developer.android.com/guide/components/foreground-services

Categories

Resources