Notificaciones

Por 9.99€ al mes tendrás acceso completo a todos los cursos. Sin matrícula ni permanencia.

Básica

El código para programar notifiaciones ha cambiado a partir de Android 8.

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void lanzarNotificacion(View v){
	NotificationUtils mNotificationUtils;
	if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
		// only for Oreo(8) and newer versions
		mNotificationUtils = new NotificationUtils(this, true);
	}else{
		mNotificationUtils = new NotificationUtils(this, false);
	}
	Notification.Builder nb = mNotificationUtils.getChannelNotification("Titulo", "Mensaje", R.raw.hakunamatata);
	mNotificationUtils.getManager().notify(101, nb.build());
}
public class NotificationUtils extends ContextWrapper {

    private NotificationManager mManager;
    private boolean isAndroid8;
    public static final String ANDROID_CHANNEL_ID = "com.pablomonteserin.ANDROID";
    public static final String ANDROID_CHANNEL_NAME = "ANDROID CHANNEL";

    public NotificationUtils(Context base, boolean isAndroid8) {
        super(base);
        this.isAndroid8 = isAndroid8;
        if(isAndroid8){
           createChannels();
        }
    }

    @TargetApi(26)
    public void createChannels() {
        // create android channel
        NotificationChannel androidChannel = new NotificationChannel(ANDROID_CHANNEL_ID,
                ANDROID_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
        // Sets whether notifications posted to this channel should display notification lights
        androidChannel.enableLights(true);
        // Sets whether notification posted to this channel should vibrate.
        androidChannel.enableVibration(true);
        // Sets the notification light color for notifications posted to this channel
        androidChannel.setLightColor(Color.GREEN);
        // Sets whether notifications posted to this channel appear on the lockscreen or not
		// androidChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        androidChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);

        getManager().createNotificationChannel(androidChannel);
    }

    public NotificationManager getManager() {
        if (mManager == null) {
            mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        }
        return mManager;
    }

    public Notification.Builder getChannelNotification(String title, String body,int sound) {
        Notification.Builder builder;

        if(isAndroid8){
            builder  = new Notification.Builder(getApplicationContext(), ANDROID_CHANNEL_ID);
        }else{
            builder = new Notification.Builder(getApplicationContext());
        }
        builder .setContentTitle(title)
                .setContentText(body)
                .setSmallIcon(android.R.drawable.stat_notify_more)
                .setAutoCancel(true);
        return builder;
    }
}
Notificaciones 1

Ejercicio: notificaciones

Hacer que la notificación muestre una imagen

...
Bitmap aperturaabductoresBitmap = BitmapFactory.decodeResource(getResources(),
                            R.drawable.aperturaabductores);
...
nb.setStyle(new Notification.BigPictureStyle().bigPicture(bitmap));

Notificación que abre un activity

PendingIntent

Es un envoltorio de un Intent que puede necesitar ciertos permisos para ser ejecutado. Si la aplicación dónde se está ejecutando ya tiene esos permisos, envolviendo el Intent con un PendingIntent, podremos hacer uso de dichos permisos.

Intent notificationIntent = new Intent(this, NotificacionesActivityAbierto.class);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
...
.setContentIntent(pendingIntent);

Temporizadores

Son aquellas clases que nos permiten programar tareas que se ejecutarán al cabo de un tiempo.

Recogemos 3 grandes tipos:

  • CounterTimeDown: nos permite ejecutar un evento cada cierto tiempo (siempre que la aplicación esté abierta, si la app está en segundo plano, dará problemas).CountDownTimer timer = new CountDownTimer(3000, 1000) { private int counter; public void onTick(long millisUnistilFinished) { Log.d("traza", "Se ejecuta el timer"); } }.start();Para cancelarlo:if(isMyServiceRunning( Servicio.class)){ CountDownTimerServiceMovil.timer.cancel(); } private boolean isMyServiceRunning(Class<?> serviceClass) { ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; }

Por 9.99€ al mes tendrás acceso completo a todos los cursos. Sin matrícula ni permanencia.