I’m trying to display some notifications in a certain moment of the day in my application with Kotlin…I found a example on Github and make my code based in it. This code make the alarm:
lateinit var preferences: SharedPreferences
@SuppressLint("ServiceCast")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
preferences = getSharedPreferences("tk.thallyssonklein.kapp.notifications", MODE_PRIVATE)
for(mov in preferences.all){
val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.set(
AlarmManager.RTC_WAKEUP,
Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, 17)
set(Calendar.MINUTE, 17)
set(Calendar.SECOND, 0)
}.timeInMillis,
PendingIntent.getBroadcast(
applicationContext,
0,
Intent(applicationContext, AlarmBroadcastReceiver::class.java).apply {
putExtra("notificationId", "tk.thallyssonklein.kapp.notifications")
putExtra("ticker", "A morning exercise")
putExtra("title", mov.key)
putExtra("text", "Do this exercise now!")
},
PendingIntent.FLAG_CANCEL_CURRENT
)
)
}
getDataFromServer()
}
I already got test if this loop is working perfectly, and it’s working, it’s run two times and make two alarms. I put to run on 17:17 and waited for this time, and nothing went show.
The AlarmBroadcastReceiver class:
package tk.thallyssonklein.kapp
/**
* Created by thall on 14/01/2018.
*/
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
class AlarmBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
(context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).notify(
intent!!.getIntExtra("notificationId", 0),
Notification.Builder(context).apply {
setSmallIcon(tk.thallyssonklein.kapp.R.drawable.ic_stretching_exercises)
setContentTitle(intent.getStringExtra("title"))
setContentText(intent.getCharSequenceExtra("text"))
setWhen(System.currentTimeMillis())
setTicker(intent.getCharSequenceExtra("ticker"))
setPriority(Notification.PRIORITY_DEFAULT)
setAutoCancel(true)
setDefaults(Notification.DEFAULT_SOUND)
setContentIntent(PendingIntent.getActivity(context, 0, Intent(context, MainActivity::class.java), 0))
}.build()
)
}
}
Obs: The app does not show any exception in log.
Someone know what’s happening here?