yo tengo una alplicacion que te recuerda una hora antes cuando tienes una cita, la cuestion es como dices que hay que pasarlo a formato tiempo, como la hora actual, como la de tu base de datos.
Esto se consigue con un Job Service ( de esto si que hay varios tutoriales ), te paso el codigo que yo tengo ( esta hecho en kotlin ).
Esta es la clase MyJobService
class MyJobService : JobService() {
internal var isWorking = false
internal var jobCancelled = false
// Called by the Android system when it's time to run the job
override fun onStartJob(jobParameters:JobParameters):Boolean {
Log.d(TAG, "Job started!")
isWorking = true
// We need 'jobParameters' so we can call 'jobFinished'
startWorkOnNewThread(jobParameters) // Services do NOT run on a separate thread
return isWorking
}
private fun startWorkOnNewThread(jobParameters:JobParameters) {
Thread(object:Runnable {
public override fun run() {
doWork(jobParameters)
}
}).start()
}
private fun doWork(jobParameters:JobParameters) {
// 60 seconds of 'working' (6000*10ms)
for (i in 0..60000)
{
recorrerMeting()
// If the job has been cancelled, stop working; the job will be rescheduled.
if (jobCancelled)
return
try
{
Thread.sleep(60000)
}
catch (e:Exception) {}
}
Log.d(TAG, "Job finished!")
isWorking = false
val needsReschedule = false
jobFinished(jobParameters, needsReschedule)
}
// Called if the job was cancelled before being finished
override fun onStopJob(jobParameters:JobParameters):Boolean {
Log.d(TAG, "Job cancelled before being completed.")
jobCancelled = true
val needsReschedule = isWorking
jobFinished(jobParameters, needsReschedule)
return needsReschedule
}
companion object {
private val TAG = MyJobService::class.java.getSimpleName()
}
//*** CREA UNA NOTIFICACION QUE INDICA EN LA PARTE SUPERIOR DE LA PANTALLA QUE HAY CITAS ***
fun creaNotificacion1(whenn: Long, notificationContent: String, ctx: Context) {
try {
;
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationIntent: Intent
val largeIcon = BitmapFactory.decodeResource(ctx.resources, R.drawable.invoice)
notificationIntent = Intent()
/* Crea PendingIntent */
val pendingIntent = PendingIntent.getActivity(ctx, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val notificationManager = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
/* Construye la notificacion */
val notificationBuilder = NotificationCompat.Builder(ctx).setWhen(whenn).setContentText(notificationContent)
.setLargeIcon(largeIcon)
.setAutoCancel(true) //Automatically delete the notification
.setSmallIcon(R.drawable.ic_add_alert_black_24dp) //Notification icon
.setContentIntent(pendingIntent)
.setContentTitle(ctx.resources.getString(R.string.aviso))
.setContentText(ctx.resources.getString(R.string.seeMeetings))
.setCategory(Notification.CATEGORY_REMINDER)
.setPriority(Notification.PRIORITY_HIGH)
.setSound(defaultSoundUri)
Objects.requireNonNull(notificationManager).notify(whenn.toInt(), notificationBuilder.build())
} catch (e: Exception) {
Log.e("Notificacion", "createNotification::" + e.message)
}
}
//*** CREA UNA NOTIFICACION QUE INDICA EN LA PARTE SUPERIOR DE LA PANTALLA QUE HAY CITAS ***
fun creaNotificacion(context: Context) {
try {
// SE ELIGE EL SONIDO
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationIntent: Intent
// SE ELIGE LA FOTO
val largeIcon = BitmapFactory.decodeResource(
context.resources,
R.drawable.invoice
)
notificationIntent = Intent()
/* Crea PendingIntent */
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(
context,
0 /* Request code */,
notificationIntent,
PendingIntent.FLAG_ONE_SHOT
)
//Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
//Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_app_notification_icon);
val channel_id = createNotificationChannel(context)
val notificationBuilder = NotificationCompat.Builder(context, channel_id!!)
.setContentTitle(resources.getString(R.string.aviso))
.setContentText(resources.getString(R.string.seeMeetings))
.setStyle(NotificationCompat.BigTextStyle().bigText(resources.getString(R.string.seeMeetings)))
.setLargeIcon(largeIcon)
.setSmallIcon(R.drawable.ic_add_alert_black_24dp) //needs white icon with transparent BG (For all platforms)
//.setColor(ContextCompat.getColor(context, R.color.colorPrimaryDark))
.setVibrate(longArrayOf(1000, 1000))
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
.setPriority(Notification.PRIORITY_HIGH)
.setAutoCancel(true)
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(
(Date(System.currentTimeMillis()).time / 1000L % Integer.MAX_VALUE).toInt() /* ID of notification */,
notificationBuilder.build()
)
} catch (e: Exception) {
Log.e("Notificacion", "createNotification::" + e.message)
}
}
fun createNotificationChannel(context: Context): String? {
// NotificationChannels are required for Notifications on O (API 26) and above.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// The id of the channel.
val channelId = "Channel_id"
// The user-visible name of the channel.
val channelName = "Application_name"
// The user-visible description of the channel.
val channelDescription = "Application_name Alert"
val channelImportance = NotificationManager.IMPORTANCE_DEFAULT
val channelEnableVibrate = true
// int channelLockscreenVisibility = Notification.;
// Initializes NotificationChannel.
val notificationChannel = NotificationChannel(channelId, channelName, channelImportance)
notificationChannel.description = channelDescription
notificationChannel.enableVibration(channelEnableVibrate)
// notificationChannel.setLockscreenVisibility(channelLockscreenVisibility);
// Adds NotificationChannel to system. Attempting to create an existing notification
// channel with its original values performs no operation, so it's safe to perform the
// below sequence.
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(notificationChannel)
return channelId
} else {
// Returns null for pre-O (26) devices.
return null
}
}
//** EL PARAMETRO FECHA QUE RECIBIMOS LO CONVIERTE EN DATE PARA SER UTILIZADO **
private fun parseFecha(fecha: String): Date {
val cal = Calendar.getInstance()
val fechaTotal = fecha.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val anio = fechaTotal[0].split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
cal.set(Calendar.YEAR, Integer.parseInt(anio[0]))
cal.set(Calendar.MONTH, Integer.parseInt(anio[1]))
cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(anio[2]))
val hora = fechaTotal[1].split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
cal.set(
Integer.parseInt(anio[2]), Integer.parseInt(anio[1]) - 1,
Integer.parseInt(anio[0]), Integer.parseInt(hora[0]),
Integer.parseInt(hora[1]), Character.MIN_RADIX
)
return cal.time
}
//** RECORRE LA TABLA MEETING Y SI COINCIDE LA FECHA ACTUAL CON LA FECHA DE LA CITA ABRE UNA NOTIFICACION INDICANDOLO **
@SuppressLint("ObsoleteSdkInt")
private fun recorrerMeting() {
val db = DataBaseHelper(this)
val cal = Calendar.getInstance()
cal.add(Calendar.HOUR, +1); // UNA HORA ANTES DE LA CITA
var fechaDeMeeting = ""
for (i in 0..db.meetingsOfAll.size - 1) {
fechaDeMeeting = db.meetingsOfAll[i].hour + " " + db.meetingsOfAll[i].date
/*println(" fecha de la base de datos: " + fechaDeMeeting)
println(" fecha del sistema ahora mismo: " + cal.getTime())
Log.i("MALGO","Fecha del meeting "+fechaDeMeeting);
Log.i("MALGO","Fecha del sistema "+cal.getTime().toString())
Log.i("MALGO","Fecha del sistema parseada "+getHoraPedido(cal.getTime()))*/
if (getHoraPedido(cal.getTime()).equals(getHoraPedido(parseFecha(fechaDeMeeting)))) {
// SE CONTROLA LA VERSION DE ANDROID, SI ES MAYOR DE OREO TIENE QUE NOTIICARSE DE OTRA FORMA
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
creaNotificacion(this)
} else{
creaNotificacion1(0, "", this)
}
}
}
}
private fun getHoraPedido(fecha1: Date): String {
val fechaFormateada = SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.getDefault()).format(fecha1)
return fechaFormateada
}
}
Y luego la llamo en la actividad principal.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val jobScheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler
val jobInfo = JobInfo.Builder(11, ComponentName(this@MainActivity, MyJobService::class.java))
// only add if network access is required
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).build()
jobScheduler.schedule(jobInfo)
val resultCode = jobScheduler.schedule(jobInfo)
if (resultCode == JobScheduler.RESULT_SUCCESS) {
} else {
}
}
Espero que te sirva de ayuda.