1+ package com.zekecode.akira_financialtracker.workers
2+
3+ import android.app.NotificationChannel
4+ import android.app.NotificationManager
5+ import android.app.PendingIntent
6+ import android.content.Context
7+ import android.content.Intent
8+ import android.os.Build
9+ import androidx.core.app.NotificationCompat
10+ import androidx.hilt.work.HiltWorker
11+ import androidx.work.Worker
12+ import androidx.work.WorkerParameters
13+ import com.zekecode.akira_financialtracker.R
14+ import com.zekecode.akira_financialtracker.ui.activities.MainActivity
15+ import dagger.assisted.Assisted
16+ import dagger.assisted.AssistedInject
17+
18+ @HiltWorker
19+ class DailyReminderWorker @AssistedInject constructor(
20+ @Assisted private val context : Context ,
21+ @Assisted workerParams : WorkerParameters
22+ ) : Worker(context, workerParams) {
23+
24+ companion object {
25+ const val CHANNEL_ID = " transaction_reminder_channel"
26+ const val NOTIFICATION_ID = 1
27+ }
28+
29+ override fun doWork (): Result {
30+ createNotificationChannel()
31+ showNotification()
32+ return Result .success()
33+ }
34+
35+ private fun createNotificationChannel () {
36+ if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .O ) {
37+ val name = " Daily Transaction Reminders"
38+ val descriptionText = " Reminds you to log your daily transactions"
39+ val importance = NotificationManager .IMPORTANCE_DEFAULT
40+ val channel = NotificationChannel (CHANNEL_ID , name, importance).apply {
41+ description = descriptionText
42+ }
43+
44+ val notificationManager = context.getSystemService(Context .NOTIFICATION_SERVICE ) as NotificationManager
45+ notificationManager.createNotificationChannel(channel)
46+ }
47+ }
48+
49+ private fun showNotification () {
50+ val intent = Intent (context, MainActivity ::class .java).apply {
51+ flags = Intent .FLAG_ACTIVITY_NEW_TASK or Intent .FLAG_ACTIVITY_CLEAR_TASK
52+ }
53+
54+ val pendingIntent = PendingIntent .getActivity(
55+ context,
56+ 0 ,
57+ intent,
58+ PendingIntent .FLAG_IMMUTABLE
59+ )
60+
61+ val notification = NotificationCompat .Builder (context, CHANNEL_ID )
62+ .setSmallIcon(R .drawable.ic_notifications)
63+ .setContentTitle(" Log Your Transactions" )
64+ .setContentText(" Don't forget to log today's transactions!" )
65+ .setPriority(NotificationCompat .PRIORITY_DEFAULT )
66+ .setAutoCancel(true )
67+ .setContentIntent(pendingIntent)
68+ .build()
69+
70+ val notificationManager = context.getSystemService(Context .NOTIFICATION_SERVICE ) as NotificationManager
71+ notificationManager.notify(NOTIFICATION_ID , notification)
72+ }
73+ }
0 commit comments