Search code examples
androidservicejsoup

How to write a service which will send me a notification if news were added on a website(jsoup parsing)?


I need to create an application which will parse a website via JSOUP. JSOUP must check for a new articles on the website. If he found a new article the app will send me a notification. I don't know how to create such kind of service. I need to create unkilled(when my app will be closed) service which will check for new articles, for example, every 1 hour and send me the notification. Can you help me how to write that unkilled service which will check the information every hour? You needn't to write the logic of checking for articles and a structure of a creating the notification, just write me the service.


Solution

  • If every one hour then WorkManager periodic job would be a good choice

    fun createConstraints() = Constraints.Builder()
                            .setRequiredNetworkType(NetworkType.UNMETERED)  // if connected to WIFI
                                                                              // other values(NOT_REQUIRED, CONNECTED, NOT_ROAMING, METERED)
                            .setRequiresBatteryNotLow(true)                 // if the battery is not low
                            .setRequiresStorageNotLow(true)                 // if the storage is not low
                            .build()
    
    fun createWorkRequest(data: Data) = PeriodicWorkRequestBuilder<LocationWorker>(12, TimeUnit.HOURS)  // setting period to 12 hours
                    // set input data for the work
                    .setInputData(data)                                                     
                    .setConstraints(createConstraints())
                    // setting a backoff on case the work needs to retry
                    .setBackoffCriteria(BackoffPolicy.LINEAR, PeriodicWorkRequest.MIN_BACKOFF_MILLIS, TimeUnit.MILLISECONDS)
                    .build()
    
    fun startWork() {
        // set the input data, it is like a Bundle
        val work = createWorkRequest(Data.EMPTY)
        /* enqueue a work, ExistingPeriodicWorkPolicy.KEEP means that if this work already existits, it will be kept
        if the value is ExistingPeriodicWorkPolicy.REPLACE, then the work will be replaced */
        WorkManager.getInstance().enqueueUniquePeriodicWork("Smart work", ExistingPeriodicWorkPolicy.KEEP, work)
    
        // Observe the result od the work
        WorkManager.getInstance().getWorkInfoByIdLiveData(work.id)
            .observe(lifecycleOwner, Observer { workInfo ->
                if (workInfo != null && workInfo.state == WorkInfo.State.SUCCEEDED) {
                    // FINISHED SUCCESSFULLY!
                }
            })
    }
    

    Here is the full example of how to use WorkManager based on your needs.

    work manager has doWork() method where you can create notification if needed

    Here is a sample of how to create a notification

    val intent = Intent(this, AlertDetails::class.java).apply {
        flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
    }
    val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
    
    val builder = NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.notification_icon)
            .setContentTitle("My notification")
            .setContentText("Hello World!")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            // Set the intent that will fire when the user taps the notification
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
    

    Make sure to create a notification channel while you are using the notification.

    In here explained detailly how to create a notification.