首页 > 解决方案 > 如果在网站上添加了新闻(jsoup 解析),如何编写一个会向我发送通知的服务?

问题描述

我需要创建一个将通过 JSOUP 解析网站的应用程序。JSOUP 必须检查网站上的新文章。如果他发现了一篇新文章,该应用程序会向我发送通知。我不知道如何创建这样的服务。我需要创建 unkilled(当我的应用程序将关闭时)服务,它将检查新文章,例如,每 1 小时向我发送通知。你能帮我写一个每小时检查一次信息的无害服务吗?您无需编写检查文章的逻辑和创建通知的结构,只需向我编写服务即可。

标签: androidservicejsoup

解决方案


如果每隔一小时,那么WorkManager定期作业将是一个不错的选择

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!
            }
        })
}

这是如何WorkManager根据您的需要使用的完整示例。

工作经理有doWork()方法,您可以在需要时创建通知

以下是如何创建通知的示例

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)

确保在使用通知时创建通知渠道。

这里详细解释了如何创建通知。


推荐阅读