0

Estoy intentando implementar las notificaciones en mi app de Android, y no veo ningún tutorial (algo raro) sobre cómo gestionar las fechas y las horas de una base de datos para que cuando coincidan con el sistema, me lance una notificación.

Supongo que la idea es pasar la fecha y la hora a milisegundos, osea que a partir de este registro cuente el sistema X milisegundos para repetir la alarma en el sistema..

Aunque la duda que me surge respecto a esto, es como puedo hacer que esto se de forma indefinida cuando el usuario cree la notificacion o la edite...

Alguna idea?

1
  • Bienvenido, debes agregar lo que investigaste o trataste, revisa Cómo preguntar, saludos.
    – Jorgesys
    el 26 jun. 2020 a las 16:44

2 respuestas 2

2

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.

1
  • Muchas gracias! :)
    – Ruben LA
    el 28 jun. 2020 a las 16:05
0

Lo que tienes pensado lo puedes lograr con un Servicio en Android, el problema de implementar un servicio es que cuando el dispositivo se encuentra sobrecargado el SO lo desstruye para liberar RAM. Este sería el código para el Servicio

AlarmService.java
public class AlarmService extends Service {

    final static String DATA_BASE_NAME = "alarm_data_base";
    private NotificationCompat.Builder mBuilder;
    private NotificationManager notification;
    private SQLiteDatabase alarmDB;

    @Override
    public void onCreate() {
        super.onCreate();
        //Crear la notificación 
        //...
        //Inicalizar la base de datos donde se encuentran las alarmas
        AdminSQLiteOpenHelper sqLiteOpenHelper = new AdminSQLiteOpenHelper(this, DATA_BASE_NAME, null, 1);
        alarmDB = sqLiteOpenHelper.getWritableDatabase();
    }

    /**
     * Este método se ejecuta cuando se inicia o reinicia el proceso, en caso de que
     * Android lo haya finalizado para liberar RAM
     */
    @Override
    public int onStartCommand(Intent intenc, int flags, int idArranque) {
        //Creas un contador de tiempo, el valor 10000 es el intervalo de tiempo en que
        //se llamará al método onTick() en milisegundos, un valor menor hace la alarma más
        //precisa pero sobrecarga un poco más al sistema y puede crear una mala experiencia de ususario 
        //en dispositivos con poca RAM
        new CountDownTimer(Long.MAX_VALUE, 10000) {

            @Override
            public void onTick(long millisUntilFinished) {
                //Aquí verificas si hay alguna alarma a esa hora
                showNotification();
            }

            @Override
            public void onFinish() {

            }
        }.start();
        return Service.START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void showNotification() {
        //Obtener la fecha actual en minutos
        int time = getMinutes(new GregorianCalendar());
        Cursor cursor = alarmDB.rawQuery("select alarm_name from alarms where time=" + time, null);
        //Comprobar si en la hora actual hay alguna alarma
        if (cursor.moveToFirst()) {
            //Ejecutar alarma
            mBuilder.setContentText(cursor.getString(0));
            notification.notify(0, mBuilder.build());
        }
        cursor.close();
    }

    /**
     * Convierte la fecha del GregorianCalendar en un int que representa el total de minutos
     *
     * @param calendar Fecha para convertir en minutos
     * @return Total de minutos que han trasncurrido desde el inicio del año hasta la fecha
     * del GregorianCalendar
     */
    public static int getMinutes(GregorianCalendar calendar) {
        int day = calendar.get(Calendar.DAY_OF_YEAR);
        //Total de minutos que trae un día completo
        int dayMin = 1440;
        int minutes = (day * dayMin);
        minutes += calendar.get(Calendar.MINUTE);
        minutes += (calendar.get(Calendar.HOUR_OF_DAY) * 60);
        return minutes;
    }
}

AndroidManifest.xml
<service android:name=".AlarmService"
    android:description="@string/app_name"
    android:enabled="true" android:label="AlarmService" />

Para que no muera el proceso lo mejor es utilizar un Broadcast para lanzar el proceso cada vez que se llame. Para ello utilizarías el Servicio de Alarma por defecto que tiene el SO. Este sería el código:

AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        //Iniciar el servicio
        Intent background = new Intent(context, AlarmService.class);
        context.startService(background);
    }
}

AndroidManifest.xml
<receiver android:name=".AlarmReceiver">
    <intent-filter>
        <action android:name="REFRESH_SERVICE" />
    </intent-filter>
</receiver>

Por último en la actividad de la alarma debes instanciar el Bradcast para que se ejecute a la par con el sevicio de alarma del SO.

MainActivity.java
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Iniciar el Broadcast para que no muera el proceso
        String alarm = Context.ALARM_SERVICE;
        AlarmManager alarmManager = (AlarmManager) getSystemService(alarm);
        Intent intent = new Intent("REFRESH_SERVICE");
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 123456789, intent, 0);
        int type = AlarmManager.RTC_WAKEUP;
        //Intervalo de tiempo en millisegundos que se ejecutará onReceive en el BroadCast
        long interval = 60000;
        alarmManager.setRepeating(type, System.currentTimeMillis(), interval, pendingIntent);
    }
}

Espero haberte ayudado con esto. Sólo debes añadir las alarmas a la base de datos usando la fecha convertida en minutos con el método getMinutes () y listo.

1
  • Muchas gracias!!
    – Ruben LA
    el 28 jun. 2020 a las 16:05

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.