![](/img/trans.png)
[英]How to send notification with a delay when a condition is met in Android Studio
[英]How to receive a notification every hour if a condition is met on android studio?
好的,我知道我的標題可能會令人困惑,所以我會稍微解釋一下。 我可以訪問 API,我希望:每小時,我的應用程序在后台向此 API 發出請求,如果 API 響應包含更多或更少的最近日期,則發送通知。 要檢查答案是否是最近的,我已經能夠做到,但我想知道的是如何每小時在后台發出這個請求,然后如何在通知中發送這個請求的數據(我已經知道如何創建通知,這不是問題)。 我被困了一段時間,我想答案將是與服務器有關的東西,一個我完全不知道的域
您可以嘗試 AlarmManager 和 BroadcastReceiver 重復時間為1h
這是一個示例(對不起,它是 Kotlin):
val flag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
} else PendingIntent.FLAG_UPDATE_CURRENT
val intent = Intent(context, YourReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, flag)
val alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
alarmManager.setRepeating(
AlarmManager.RTC,
timeInMillis,
1000 * 60 * 60, //1h in millis
pendingIntent
)
然后編寫 YourReceiver 並覆蓋 onReceive function
class YourReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
//call api & check your requirements then push notification
}
}
顯現:
<application>
...
<receiver android:name=".YourReceiver" />
</application>
或者您可以嘗試定期工作請求: https://medium.com/@sumon.v0.0/android-jetpack-workmanager-onetime-and-periodic-work-request-94ace224ff7d
如果 API 已經存在,則不需要服務器。 您只需安排每小時在設備上完成的工作。 您可以為此使用 WorkScheduler。 如果需要編寫 API,那么是的,您需要一個服務器並且需要學習如何編寫 web 服務。 但這遠遠超出了堆棧溢出問題的規模,您可以在谷歌上搜索各種教程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.