android - 如果在网站上添加了新闻(jsoup 解析),如何编写一个会向我发送通知的服务?
问题描述
我需要创建一个将通过 JSOUP 解析网站的应用程序。JSOUP 必须检查网站上的新文章。如果他发现了一篇新文章,该应用程序会向我发送通知。我不知道如何创建这样的服务。我需要创建 unkilled(当我的应用程序将关闭时)服务,它将检查新文章,例如,每 1 小时向我发送通知。你能帮我写一个每小时检查一次信息的无害服务吗?您无需编写检查文章的逻辑和创建通知的结构,只需向我编写服务即可。
解决方案
如果每隔一小时,那么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)
确保在使用通知时创建通知渠道。
在这里详细解释了如何创建通知。
推荐阅读
- ios - 如何将此日期格式转换为我们在objective-c中的常规日期
- python - 当用户在网站上注册时如何为用户创建单独的表
- python - 学习 Wagtail 时 Python 模块名称冲突
- android - 我需要增加库模块的版本代码吗?
- python - 创建一个给定长度加起来为 1 的数字数组
- c - Swiss Ephemeris program swetest - Windows 和 Ubuntu 中的不同输出
- android - com.google.android.gms.common.api.ApiException: 12500,在 google 的 android firebase 项目中登录
- xml - 如何在 DataPower 中使用 XSLT 转换基于一个 XML 文件的多个 XML 并将所有请求调用到 MQ
- swiftui - Watch 上 SwiftUI 按钮中奇怪的内部视图
- reactjs - 表单上的 React-onSubmit 函数不起作用