警报管理器无法执行长期任务 [英] Alarm manager is not working with long term tasks

查看:95
本文介绍了警报管理器无法执行长期任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

设置警报后2到3分钟,我的警报管理器正在工作.但是,当我将闹钟"设置为30分钟之后或之后的一天不会响起.

My Alarm manager is working when I set the Alarm, after 2 or 3 minutes. But when I set Alarm for a day after or after 30 minutes it doesn't rings.

主要活动:

    addTaskIMBTN.setOnClickListener {

        val dialog: AlertDialog.Builder = AlertDialog.Builder(this)
        val view: View = layoutInflater.inflate(R.layout.dialog_task, null)

        //time picker and date picker
        val timepicker: Button = view.findViewById(R.id.timeSelector)
        val datePicker: Button = view.findViewById(R.id.dateSelector)
        val deadlineTXT: TextView = view.findViewById(R.id.dateTimeShower)
        val deadtimeTXT: TextView = view.findViewById(R.id.timeShower)

        todoName = view.findViewById(R.id.taskET2)

        val hour = c.get(Calendar.HOUR_OF_DAY)
        val minute = c.get(Calendar.MINUTE)

        timepicker.setOnClickListener {
            timePickerDialog =
                TimePickerDialog(
                    this,
                    { _, p1, p2 ->
                        c.set(Calendar.HOUR_OF_DAY, p1)
                        c.set(Calendar.MINUTE, p2)
                        c.set(Calendar.SECOND, 0)
                        deadtimeTXT.text = "Time : $p1:$p2"


                    }, hour, minute, true
                )
            timePickerDialog.show()
        }
        val mYear = c.get(Calendar.YEAR)
        val mMonth = c.get(Calendar.MONTH)
        val mDay = c.get(Calendar.DAY_OF_MONTH)

        datePicker.setOnClickListener {
            datePickerDialog = DatePickerDialog(
                this,
                { _: DatePicker, year, monthOfYear, dayOfMonth ->
                    deadlineTXT.text =
                        "Date : " + dayOfMonth.toString() + "-" + (monthOfYear + 1) + "-" + year
                    c.set(Calendar.YEAR, year)
                    c.set(Calendar.DAY_OF_MONTH, dayOfMonth)
                    c.set(Calendar.MONTH, monthOfYear)
                },
                mYear,
                mMonth,
                mDay
            )
            datePickerDialog.show()
        }

        //positive button function
        dialog.setView(view)
        dialog.setTitle("Add a Task")
        dialog.setPositiveButton("Add") { _: DialogInterface, _: Int ->
            if (todoName.toString().isEmpty() || todoName.text.isEmpty()) {
                Toast.makeText(
                    applicationContext,
                    "Please add a name for the task",
                    Toast.LENGTH_LONG
                ).show()
            } else {
                Log.i("today's time", c.time.toString())

                val simpleDateFormat = SimpleDateFormat("d MMM 'at' HH:mm")
                date = c.time
                val string = simpleDateFormat.format(date)
                val newInt : Int = c.timeInMillis.toInt()

                val intent : Intent = Intent(this@TasksActivity, ReminderBroadcast::class.java )
                val pendingIntent = PendingIntent.getBroadcast(this@TasksActivity, newInt, intent, PendingIntent.FLAG_UPDATE_CURRENT)

                val alarmManager : AlarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
                alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.timeInMillis, pendingIntent)

                tdItem.itemName = todoName.text.toString()
                tdItem.isCreatedAt = string
                tdItem.toDoId = todoID
                tdItem.isCompleted = false
                dbHandler.addTasks(tdItem)
                refreshList()
            }
        }
        dialog.setNegativeButton("Cancel") { _: DialogInterface, _: Int ->

        }
        dialog.show()
    }

    backBTN.setOnClickListener {
        finish()
    }
}

通知频道:

fun notificationChannel(){
    val uri  = Uri.parse("android.resource://" + this.packageName + "/" + R.raw.checked_it)

    val audioAttributes = AudioAttributes.Builder()
        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
        .setUsage(AudioAttributes.USAGE_ALARM)
        .build()

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        val name : CharSequence = "NotifyMeForDeadline";
        val description : String = "Channel for Deadline Reminder"
        val importance = NotificationManager.IMPORTANCE_HIGH
        val nc : NotificationChannel = NotificationChannel("notifyDeadline", name, importance)
        nc.setSound(uri, audioAttributes)
        nc.description = description

        val notificationManager = getSystemService(NotificationManager::class.java)
        notificationManager.createNotificationChannel(nc)
    }
}

广播接收方:

override fun onReceive(p0: Context, p1: Intent) {
    p0.startActivity(p1)
    val intent : Intent = Intent(p0, TasksActivity::class.java)
    val pendingIntent = PendingIntent.getActivity(p0, 0, intent, PendingIntent.FLAG_ONE_SHOT)
    val uri  = Uri.parse(Uri.parse("android.resource://" + p0.packageName + "/" + R.raw.checked_it)
        .toString())
    Toast.makeText(p0, "Recieved", Toast.LENGTH_LONG).show()
    val builder : NotificationCompat.Builder = NotificationCompat.Builder(p0, "notifyDeadline")
        .setSmallIcon(R.drawable.ic_baseline_alarm_24)
        .setContentTitle("Reminder from Checked-It")
        .setContentText("Hey, are you working on your tasks or just procrastinating?")
        .setPriority(NotificationCompat.PRIORITY_HIGH)
        .setSound(uri)
        .setContentIntent(pendingIntent)

    val notificationManagerCompat = NotificationManagerCompat.from(p0)
    notificationManagerCompat.notify((((Date().getTime() / 1000L) % Integer.MAX_VALUE).toInt()), builder.build())

}

我可以找到解决问题的方法,所以请帮帮我....我很乐意听您的答复.谢谢!!

I can find the solution for this so please help me out....I'll be pleased to listen your answer. Thank You!!

安排任务后再次打开应用程序时,通知也不会显示.

And Notification also doesn't show up when after scheduling the task I open the app again.

推荐答案

此处是警报管理器的有效示例.只要您需要,此示例就可以持续工作.

Here is a working sample of the Alarm Manager. This example works consistently for as long as you need it to.

如何在Fragment中使用Android AlarmManager在科特林吗?

由于重新启动后所有警报均被取消.您还需要使用广播接收器处理设备重启.您可以在互联网上找到更多信息.

Since all alarms are cancelled on reboot. You will also need to handle Device Reboot with Broadcast receivers. You can find more information on the internet.

除此之外,这是最大优先级通知的工作示例:

In addition to that, here is a working sample of Max Priority Notifications:

private fun sendInternetDaysLeftNotification(context: Context) {
        // This is used for opening application when the notification is clicked
        val intent: Intent = Intent(context, ProfileActivity::class.java)
            .putExtra(INTENT_EXTRA_INTERNET_DAYS_LEFT, contentText)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        intent.action = INTENT_ACTION_INTERNET_DAYS_LEFT_DIALOG
        val pendingIntent: PendingIntent = PendingIntent.getActivity(
            context,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT
        )

        val channelId: String = context.resources.getString(R.string.internetDaysLeftNotificationsChannelId)
        val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        val notificationBuilder: NotificationCompat.Builder = NotificationCompat.Builder(context, channelId)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle(contentTitle)
            .setContentText(contentText)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setPriority(NotificationCompat.PRIORITY_MAX)

        val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(channelId, DEFAULT_NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH)
            notificationManager.createNotificationChannel(channel)
        }

        notificationManager.notify(Random.nextInt(0, 100), notificationBuilder.build())
    }

这篇关于警报管理器无法执行长期任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆