Notificaciones push

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

1. El código de nuestra clase en Android sería el siguiente. Con este código obtendremos un deviceToken que habrá que pegar a nuestro código PHP. En condiciones normales, este token serán almacenado en la base de datos en el servidor:

FirebaseInstanceId.getInstance().getInstanceId().addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() { 
   @Override public void onComplete(@NonNull Task<InstanceIdResult> task) { 
      if(!task.isSuccessful()){
         Log.w("TOKEN", "error al obtener el token"); 
         return;
      } else { 
         Log.w("TOKEN", task.getResult().getToken()); 
      } 
   } 
});

2. Debemos crear un proyecto en firebase. Para ello, podemos loguearnos en el android studio en firebase y crear un nuevo proyecto.

Notificaciones push 1

3. Get started by adding Firebase to your app -> Android -> Nos pide los siguientes datos:

Android package name -> Lo obtengo en el build.gradle (del módulo) -> ApplicationId

Descargamos el fichero json. En el pantallazo se nos indica donde colocarlo.

Añadimos los códigos que nos da en el build.gradle (del proyecto) y en el buid.gradle (del módulo)

4. La siguiente clase tiene dos métodos importantes:

onMessageReceived: gestiona la recepción de las notificaciones push de Firebase.

showNotification: muestra una notificación en el móvil.

package oo;

public class MyNotificationService extends FirebaseMessagingService {
	@Override
	public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
		RemoteMessage.Notification notification = remoteMessage.getNotification();
		if (notification != null) {
			String message = notification.getBody();
			showNotification(message);
		}
	}

	@Override
	public void onNewToken(@NonNull String token) {
	}

	private void showNotification(String message){ 
		Intent intent = new Intent(this, MainActivity.class); 
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT); 
		String channelID = "channel"; 
		Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
		NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelID) .setSmallIcon(R.drawable.android1) .setContentTitle(getString(R.string.app_name)) .setContentText(message) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); 
		NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		// Since android Oreo notification channel is needed. 
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 
			NotificationChannel channel = new NotificationChannel(channelID, "Channel human readable title", NotificationManager.IMPORTANCE_DEFAULT); 
			notificationManager.createNotificationChannel(channel); 
		} 
		notificationManager.notify(0 /* ID of notification */, builder.build()); 
	} 
}
}

1. Con esto, ya podríamos probar nuestra aplicación en firebase yendoa firebase -> Grow -> Cloud Messaging -> Escribimos los datos del mensaje -> Send test message -> Escribimos el token del móvil al que mandamos el mensaje.

2. Desarrollamos un código php para enviar las peticiones a firebase y que este se las envíe al móvil. Para poder ejecutar el comando composer en la consola, previamnete necesitamos tenerlo instalado. Podemos descargarlo desde la página de composer.
Instalamos las librerías de composer en un proyecto de nuestro servidorcomposer

require kreait/firebase-php ^4.35. notificaciones.php
require __DIR__.'/vendor/autoload.php';
use Kreait\Firebase\Messaging\CloudMessage; use Kreait\Firebase\Factory;
$factory = (new Factory())->withServiceAccount('firebase-adminsdk.json');
$messaging = $factory->createMessaging(); 
$deviceToken = "fEC_mu5UsYk:APA91bFl1xyOWhPcqqEeZg8wj0Pm3_zHwTv8dxh5n7dHG_jXK1Liuxe4lFT8vLSCGnWR3JSKmfvv_HWVMRkj1AhlMlwUhgSkWDE2KONWZLxTmdDpi1cT9UoySQpIPZzjAAezgEkq3e4C";
$body = "this is body";
$title = "this is title";
$message = CloudMessage::fromArray([ 'token' => $deviceToken, 'notification' => array("body"=>$body, "title"=>$title) // optional ]); 
var_dump($messaging->send($message));

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