如何解决在特定时间关闭应用程序时安排Android功能
我想创建一个每天晚上20点发出通知的应用程序。为此,我需要安排一个每天20点执行的函数的时间。解决此问题的最佳方法是什么?我该怎么用?
这是我要执行的功能:
private fun throwNotification() {
notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val intent = Intent(applicationContext,MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this,intent,PendingIntent.FLAG_UPDATE_CURRENT)
notificationChannel = NotificationChannel(channelId,description,NotificationManager.IMPORTANCE_HIGH)
notificationChannel.enableLights(true)
notificationChannel.lightColor = Color.RED
notificationChannel.enableVibration(true)
notificationManager.createNotificationChannel(notificationChannel)
builder = Notification.Builder(this,channelId)
.setContentTitle("Test")
.setContentText("This is a test notification")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setChannelId(channelId)
notificationManager.notify(0,builder.build())
}
解决方法
您应该关注以下任务。
- 该功能应在正好20点执行。
- #1应该每天重复一次。
- 即使应用已关闭,也应推送通知。
- 以上问题与设备是否重新启动无关。
我发现正在遵循的解决方案,要求该应用程序至少应启动一次。
#1〜3可以由AlarmManager实现。 在应用首次启动时,请调用以下代码来注册 alarmIntent 。
private var alarmMgr: AlarmManager? = null
private lateinit var alarmIntent: PendingIntent
alarmMgr = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmIntent = Intent(context,YourAlarmReceiver::class.java).let { intent ->
PendingIntent.getBroadcast(context,intent,0)
}
// Set the alarm to start at 20:00.
val calendar: Calendar = Calendar.getInstance().apply {
timeInMillis = System.currentTimeMillis()
set(Calendar.HOUR_OF_DAY,20)
set(Calendar.MINUTE,0)
set(Calendar.SECOND,0)
}
// setRepeating() lets you specify a precise custom interval--in this case,// 1 day.
alarmMgr?.setRepeating(
AlarmManager.RTC_WAKEUP,calendar.timeInMillis,1000 * 60 * 60 * 24,alarmIntent
)
在这里, alarmIntent 将在每20点调用 YourAlarmReceiver 的onReceive()。 因此,您只需要在此onReceive()内部调用 throwNotification()。
#4也很简单,可以通过监听BOOT_COMPLETED事件来实现。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。