So I was creating a Tasks Application, where user can add and delete tasks, I have given this option to remind the task after 4 hour through a notification. The notification has a 'Done' action which should delete the task from the RoomDB, but I can't figure out how to do so.
I am very new to Android dev, don't know much. I tried using a thread inside Broadcast Receiver which runs the Dao delete task function but it doesn't work while the app is closed (not even present in recent apps)
Using WorkManager:
This is my BroadcastReceiver which handles the action from notification
class TaskDone: BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val text: String? = intent.getStringExtra("text")
val notificationId: Int = intent.getIntExtra("notificationId", 1)
val notificationManager = context.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.cancel(notificationId)
val workerRequest = OneTimeWorkRequest.Builder(DeleteTask::class.java)
.setInputData(
Data.Builder()
.putString("text", text)
.build()
)
.build()
WorkManager.getInstance(context).enqueue(workerRequest)
Toast.makeText(context, "Done: $text", Toast.LENGTH_SHORT).show()
}
}
This is my Worker Class
class DeleteTask(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
override fun doWork(): Result {
TaskDatabase.createDatabase(applicationContext) //edit
val taskDao = TaskDatabase.getDatabase().getTaskDao()
val text = inputData.getString("text")
CoroutineScope(Dispatchers.IO).launch {
taskDao.deleteTaskByText(text!!)
}
return Result.success()
}
}
But this still doesn't solve the issue. It does work while the app is open or is in recent apps section but not while the app is completely closed(removed from recents too)
Edit: i forgot to create an instance of the db before accessing the dao. after i did, it works. the above code now works fine.
You can use WorkManager
for this task
Schedule a One Time Work task to do this and be ensured that this will be done and compatibility is ensured across a lot of Android version
https://developer.android.com/topic/libraries/architecture/workmanager