Paolo Donato Navarro
Paolo Donato Navarro

Reputation: 149

Android notification service not working/not showing

I want to have a service that runs forever and send notifications every day at 6pm, but for some reazon mi service stops working or something wrong happens after a few hours, and I don't have any notifications at 6pm.

Here is my code, I'm 100% sure my notifications data is there, I use a local database

class NotificationService : AppService() {

    private val timer: Timer = Timer(false)
    private var wakeLock: PowerManager.WakeLock? = null
    private var isServiceStarted = false
    private var notifications = emptyArray<INotification>()
    private lateinit var notificationController: INotificationServiceController

    private val calendar: Calendar = Calendar.getInstance().apply {
        timeInMillis = System.currentTimeMillis()
        set(Calendar.HOUR_OF_DAY, 18)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        super.onStartCommand(intent, flags, startId)

        notificationController = adaptersBuilder.notificationServiceController
        startService()

        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onDestroy() {
        super.onDestroy()
        isServiceStarted = false
        notificationController.setServiceState(ServiceStates.STOPPED.name)
        notificationController.onDestroy()
        timer.cancel()
    }

    private fun checkDBTask() {
        Log.d("NOTIFICATION", "Checking db")
        notificationController.updateNotifications()
        notificationController.getTodayNotifications { notifications ->
            this.notifications = notifications.toTypedArray()

            val now = Calendar.getInstance()
            if (now.get(Calendar.HOUR_OF_DAY) == 18 && now.get(Calendar.MINUTE) < 1) sendNotifications()
        }

    }

    private fun startService() {
        if (isServiceStarted) return
        isServiceStarted = true
        notificationController.setServiceState(ServiceStates.STARTED.name)
        wakeLock = (getSystemService(Context.POWER_SERVICE) as PowerManager).run {
            newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "NotificationService::lock").apply {
                acquire(500)
            }
        }

        GlobalScope.launch(Dispatchers.IO) {
            while (isServiceStarted) {
                launch(Dispatchers.IO) {
                    checkDBTask()
                }
                delay(1*60*1000)
            }
            Log.d("NOTIFICATION", "Notification service stopped")
        }
    }

    private fun sendNotifications() {
        val alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)

        val resultIntent = Intent(this, MainActivity::class.java)
        resultIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP
        resultIntent.putExtra("data", "fromNotification")

        val resultPendingIntent: PendingIntent? = PendingIntent.getActivity(
            this,
            0,
            resultIntent,
            PendingIntent.FLAG_UPDATE_CURRENT
        )

        notifications.forEach { notificationData ->

            val notification = NotificationCompat.Builder(this, NotificationsValues.CHANEL_ID)
                .setContentIntent(resultPendingIntent)
                .setSmallIcon(R.drawable.safin_icon)
                .setContentTitle(notificationData.title)
                .setContentText(notificationData.description)
                .setStyle(
                    NotificationCompat.BigTextStyle()
                        .bigText(notificationData.description))
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setSound(alarmSound)
                .setAutoCancel(true)
                .build()
            NotificationManagerCompat.from(this).notify(notificationData.movementId ?: 0, notification)
        }
    }
}

I used an alarm manager before, but that doesn't worked. So I try this.

Upvotes: 0

Views: 306

Answers (1)

Paolo Donato Navarro
Paolo Donato Navarro

Reputation: 149

Services in android 8.0 can be killed and some times don't start again, the WorkManager is the right class for this type of tasks. So, I changed my notifications service to a WorkManager.

https://medium.com/androiddevelopers/workmanager-periodicity-ff35185ff006 This guide help me a lot.

Upvotes: 1

Related Questions