Уведомление Таймер будильника не работает при попытке установить часы (в тиках) больше 24 (Kotlin) - PullRequest
0 голосов
/ 26 мая 2020

Я новый android разработчик, поэтому, пожалуйста, go полегче :) , поэтому я попытался создать его с помощью YouTube, и он работал только на текущий день

Пример: сейчас время 17:00, и вы устанавливаете его на 18:00, он отправит уведомление

Но когда вы пытаетесь установить его в 16:00, приложение преобразует время и вычисляет количество времени в тиках, когда я вычисляю часы из тиков, которые возвращает мое приложение, все соответствует но когда мы запускаем тест, чтобы увидеть, регистрирует ли приложение уведомление на следующий день, похоже, что он не работает.

Код:

findViewById<Button>(R.id.setTime).setOnClickListener {
            var timePickerDialog = TimePickerDialog(this@MainActivity,
                TimePickerDialog.OnTimeSetListener { timePicker, hourOfDay, minutes ->
                    hourNotif = hourOfDay
                    minNotif = minutes
                    var realMin:String
                    var realHour:Int

                    if (hourOfDay == 0){
                        realHour = 12
                    }else{
                        realHour = hourOfDay
                    }
                    if (minutes < 10){
                        realMin =  "0" + minutes
                    }else{
                        realMin = minutes.toString()
                    }


                    if (hourOfDay < 12) {
                        findViewById<Button>(R.id.setTime).text =
                            (realHour.toString() + ":" + realMin + " AM")
                    }else if (hourOfDay == 12){
                        findViewById<Button>(R.id.setTime).text =
                            (realHour.toString() + ":" + realMin.toString() + " PM")
                    }else{
                        findViewById<Button>(R.id.setTime).text =
                            ((realHour - 12).toString() + ":" + realMin.toString() + " PM")
                    }
                    if (findViewById<Switch>(R.id.enaNotif).isChecked) {
                        setTimeNotf()
                    }
                }, 0, 0, false)
            timePickerDialog.show()
        }
        fun setTimeNotf(){
        val notifSeter = getSharedPreferences(PREFABS().PREFS_NAME3, Context.MODE_PRIVATE)
        val intent = Intent(this, Notification_reciever::class.java)
        val pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0)

        if (hourNotif == 0){
            hourNotif = notifSeter.getString(PREFABS().NOTFTIM, "")!!.split("~")[0].toInt()
        }

        val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager

        var timeAtButtonClick = System.currentTimeMillis()
        var hour = LocalDateTime.now().toString().split("T")[1].split(".")[0].split(":")[0].toInt()
        var min = LocalDateTime.now().toString().split("T")[1].split(".")[0].split(":")[1].toInt()
        if (hourNotif.toInt() < hour.toInt()){
            timeFromApp = ((((hourNotif.toInt() - hour.toInt()) + 24) * 3600000) + (((minNotif.toInt() - min.toInt()) + 60) * 60000)).toLong()
            Log.e("asaaaad", "asda")
        }else if (hourNotif == hour) {
            if (minNotif < min){
                timeFromApp = ((((hourNotif.toInt() - hour.toInt()) + 24) * 3600000) + (((minNotif.toInt() - min.toInt()) + 60) * 60000)).toLong()
                Log.e("asaaaad", "asdasda")
            }else{
                timeFromApp = (((hourNotif.toInt() - hour.toInt()) * 3600000) + ((minNotif.toInt() - min.toInt()) * 60000)).toLong()
                Log.e("aszzz", "zzc")
            }
        } else {
            timeFromApp =
                (((hourNotif.toInt() - hour.toInt()) * 3600000) + ((minNotif.toInt() - min.toInt()) * 60000)).toLong()
            Log.e("asd", "asda")
        }
        Log.e("Time: ", timeFromApp.toString())
        Log.e("Hour Notif", hourNotif.toString())
        Log.e("Time hour: ", hour.toString() + " " + (hourNotif - hour))
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, timeAtButtonClick + timeFromApp, AlarmManager.INTERVAL_DAY, pendingIntent)

        var editor = notifSeter.edit()
        editor.clear()
        editor.putBoolean(PREFABS().NOTF, findViewById<Switch>(R.id.enaNotif).isChecked)
        editor.putString(PREFABS().NOTFTIM, (hourNotif.toString() + "~" +  if (minNotif < 10) "0" + minNotif.toString() else minNotif.toString()))
        editor.commit()
    }
fun createNotif(){
        var importance = NotificationManager.IMPORTANCE_DEFAULT
        var name:CharSequence = "Lost New Quote"
        var description = "A new lost quote has been selected"
        val channel = NotificationChannel("lostQuote", name, importance)
        channel.description = description

        val notificationManager = getSystemService(NotificationManager::class.java)
        notificationManager.createNotificationChannel(channel)
    }
class Notification_reciever: BroadcastReceiver() {


    override fun onReceive(context: Context?, intent: Intent?) {
        val resultIntent = Intent(context, MainActivity::class.java)
        val resultPendingIntent = PendingIntent.getActivity(context, 1, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT)
        val builder = context?.let {
            NotificationCompat.Builder(it, "lostQuote")
                .setSmallIcon(R.drawable.dharama)
                .setContentTitle("New Lost Quote!")
                .setContentTitle("Open the lost app to get your new quote!")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setContentIntent(resultPendingIntent)
                .setAutoCancel(true)
        }


        val notificationManager = context?.let { NotificationManagerCompat.from(it) }
        if (notificationManager != null) {
            if (builder != null) {
                notificationManager.notify(200, builder.build())
            }
        }



    }

}
...