▻★★★ Blog sobre el lenguaje de programación delphi, incluye software, tutoriales, aplicaciones, videos, código fuente, trucos (about delphi, tips, tutorials, applications, source code, advanced programs, code snippets )
Convertir texto a voz con Delphi en Android, IOS, Windows
Enviar notificación Push a un sólo dispositivo, con Delphi y Firebase
En el post anterior veíamos cómo enviar notificaciones a todos los dispositivos que tengan instalada una determinada app.
Pero es que también podemos enviar una notificación a un dispositivo concreto, para ello tenemos que saber el "Firebase Token" y el "Server Token"
Firebase Token
Es una serie de letras y números separados por ":" que identifican de forma única a un dispositivo.
¿Cómo se obtiene?
Pues en el post anterior veíamos que tenemos que añadir un tMemo para recibir el json de la notificación cuando la app está abierta.
el contenido del tMemo cuando se recibe la notificación podría ser algo como:
Pues ahí tienen el "Firebase Token"
Clave de servidor
Para enviar la notificación también nos hace falta el "Server Token" o "Clave del servidor" que se obtiene desde la página de Firebase- "Configuración del proyecto" - "Cloud Messaging"
Cómo enviar la notificación
Para enviar la notificación utilizaremos el componente tNetHttpClient
Creamos un programa en Delphi, con un tEdit, un tMemo, un tButton y el componente NethttpClient1
y en evento OnClic del botón "Enviar notificación" escribimos:
procedure TForm1.Button1Click(Sender: TObject);
var
Msg: string;
s1, s2: TMemoryStream;
hd: TArray menorque tnamevaluepair mayorque;
st: String;
b: TBytes;
FirebaseToken: string;
begin
deviceToken := Trim(Edit1.Text);
Msg := 'Mi primera notificación Push.';
s1 := TMemoryStream.Create;
s2 := TMemoryStream.Create;
try
NetHTTPClient1.ContentType := 'application/json';
st := '{' +
'"to": "'+FirebaseToken+'",' +
'"notification":{"priority":"hight",' +
'"title":"Título de la Notificación",'+
'"body":"'+Msg+'",'+
'"dry_run":"false"}'+
'}';
setlength(hd, 1);
b := TEncoding.UTF8.GetBytes(st);
s1.Write(b, length(b));
s1.Position := 0;
hd[0].Name:='Authorization';
hd[0].Value:='key=ANADIR AQUI EL SERVER KEY o CLAVE DE SERVIDOR';
NetHTTPClient1.Post('https://fcm.googleapis.com/fcm/send', s1, s2, hd);
s2.Position := 0;
memo1.Lines.LoadFromStream(s2, TEncoding.UTF8);
finally
s1.Free;
s2.Free;
end;
end;
Y pulsamos el botón "Enviar notificación"
Con este procedimiento sólo recibirá la notificación el dispositivo con el Firebase Token que hayamos indicado en el form.
Enviar notificaciones Push a tus dispositivos con Firebase
En este post vamos a ver paso a paso cómo enviar notificaciones Push a tus dispositivos con Firebase y Delphi
He supuesto que se ha publicado anteriormente en Google Play una app y se quiere enviar notificaciones a los usuarios que la tengan instalada.
Esta notificación la recibirán tengan abierta o no la app.
El proceso puede ser un poco tedioso al principio, pero una vez que se configure todo, cada vez que se quiera enviar una notificación habría que crear una "nueva campaña" (punto 4) indicando el texto del mensaje a enviar.
Empecemos...
1) CONFIGURANDO FIREBASE
Ir a https://console.firebase.google.com y creamos un nuevo proyecto.
Ponemos un nombre al proyecto y pulsamos sobre el botón "Continuar"
En la siguiente pantalla deshabilitamos Google Analytics y pulsamos el botón "Crear proyecto"
Y si todo ha ido bien nos aparecerá el siguiente mensaje:
Ahora tenemos que añadir al proyecto una de nuestras apps que esté publicada en Google Play, pulsando sobre el icono de Android
en la caja de texto "Android package name" indicaremos el nombre de nuestra aplicación (com.xxxxxxxxx.xxxxxxxxx), p.ej. com.misoftware.GPSPro y pulsamos el botón "Register app"
En el siguiente paso tenemos que descargar el archivo "google-services.json" haciendo clic sobre "Download google-services.json"
2) Configurando RAD STUDIO - DELPHI
Después tenemos que abrir nuestra app desde Rad Studio y acceder al menú
Project > Options... > Application > Services y hacer clic sobre el botón "Import" para importar el archivo de configuración (google-services.json)
En mi caso lo hago en la Configuración para Android 64 bits y 32 bits.
y después hay que ir a Project > Options... > Application > Entitlement List y marcar el check "Receive push notifications" también para las configuraciones de android de 64 y 32 bits.
FDeviceToken: string;
PROCEDURE TForm1.Firebase;
VAR
PushService: TPushService;
ServiceConnection: TPushServiceConnection;
Notifications: TArray menorque TPushServiceNotification mayorque;
BEGIN
PushService := TPushServiceManager.Instance.GetServiceByName(TPushService.TServiceNames.FCM);
ServiceConnection := TPushServiceConnection.create(PushService);
ServiceConnection.Active := true;
ServiceConnection.OnChange := OnServiceConnectionChange;
ServiceConnection.OnReceiveNotification := OnReceiveNotificationEvent;
FDeviceId := PushService.DeviceIDValue[TPushService.TDeviceIDNames.DeviceId];
MemoLog.Lines.Add('DeviceID: ' + FDeviceId);
MemoLog.Lines.Add('Ready to receive!');
Notifications := PushService.StartupNotifications;
IF Length(Notifications) > 0 THEN
BEGIN
MemoLog.Lines.Add('-----------------------------------------');
MemoLog.Lines.Add('DataKey = ' + Notifications[0].DataKey);
MemoLog.Lines.Add('Json = ' + Notifications[0].Json.ToString);
MemoLog.Lines.Add('DataObject = ' + Notifications[0].DataObject.ToString);
MemoLog.Lines.Add('-----------------------------------------');
END;
END;
PROCEDURE TForm1.OnServiceConnectionChange(Sender: TObject; PushChanges: TPushService.TChanges);
VAR
PushService: TPushService;
BEGIN
PushService := TPushServiceManager.Instance.GetServiceByName(TPushService.TServiceNames.FCM);
IF TPushService.TChange.DeviceToken IN PushChanges THEN
BEGIN
FDeviceToken := PushService.DeviceTokenValue[TPushService.TDeviceTokenNames.DeviceToken];
MemoLog.Lines.Add('Firebase Token: ' + FDeviceToken);
Log.d('Firebase device token: token=' + FDeviceToken);
END;
IF (TPushService.TChange.Status IN PushChanges) AND (PushService.Status = TPushService.TStatus.StartupError) THEN
MemoLog.Lines.Add('Error: ' + PushService.StartupError);
END;
PROCEDURE TForm1.OnReceiveNotificationEvent(Sender: TObject; CONST ServiceNotification: TPushServiceNotification);
VAR
MessageText: STRING;
BEGIN
MemoLog.Lines.Add('-----------------------------------------');
MemoLog.Lines.Add('DataKey = ' + ServiceNotification.DataKey);
MemoLog.Lines.Add('Json = ' + ServiceNotification.Json.ToString);
MemoLog.Lines.Add('DataObject = ' + ServiceNotification.DataObject.ToString);
MemoLog.Lines.Add('---------------------------------------');
MessageText := ServiceNotification.DataObject.GetValue('gcm.notification.body').Value;
Memo1.Lines.Add(DatetimeToStr(now) + ' Message = ' + MessageText);
MuestraNotificacion(MessageText, 0);
END;
PROCEDURE TForm1.MuestraNotificacion(MessageText: STRING; NotificationNumber: integer);
VAR
NotificationCenter: TNotificationCenter;
Notification: TNotification;
BEGIN
NotificationCenter := TNotificationCenter.create(NIL);
TRY
Notification := NotificationCenter.CreateNotification;
TRY
Notification.Name := MessageText;
Notification.AlertBody := MessageText;
Notification.Title := MessageText;
Notification.EnableSound := False;
Notification.Number := NotificationNumber;
NotificationCenter.ApplicationIconBadgeNumber := NotificationNumber;
NotificationCenter.PresentNotification(Notification);
FINALLY
Notification.DisposeOf;
END;
FINALLY
NotificationCenter.Free;
NotificationCenter.DisposeOf;
END;
END;
4) ENVIANDO LAS NOTIFICACIONES
Abrimos https://console.firebase.google.com
y se seleccionamos nuestro proyecto.
Accedemos a "Cloud Messaging" o a "Messaging" en la barra lateral izquierda
y creamos una nueva campaña, pulsando "Crear la primera campaña"
Nos pedirá que tipo de notificación queremos enviar y marcaremos sobre "Mensajes de Firebase Notifications" y después sobre el botón CREAR
En la pantalla siguiente escribimos un título: "Mi primera notificación" y el texto de la notificación y pulsamos SIGUIENTE
En la segmentación de usuarios hay que indicar el nombre de la app que hemos añadido al proyecto, para que la notificación la reciban todos los usuarios que tienen instalada en su dispositivo dicha app.
y en el punto siguiente seleccionamos la opción de enviar AHORA.
Después pulsamos el botón REVISAR y en la ventana siguiente pulsamos sobre PUBLICAR
y con eso tendremos nuestra primera notificación enviada a los usuarios que tengan instalada la app en su dispositivo.
Muy importante: No esperen que la notificación se reciba inmediatamente en el dispositivo, tarda un poco, en las pruebas que he hecho se recibe como máximo entre 2 y 10 minutos, aunque dependerá del número de usuarios que tengan instalada la app.
Simulación del movimiento de los electrones en un campo electrico
Espectacular simulación realizada con OpenGL del movimiento de los electrones cuando atraviesan un campo eléctrico. Como muestra la image...
-
Seguidamente os dejo una lista bastante amplia de funciones escritas en Delphi que se utilizan cuando estamos programando una aplicación q...
-
Para trabajar con archivos pdf dentro de tu aplicación Delphi tienen que seguir los siguientes pasos: 1) Asegurarte que tienes la última ver...
-
A continuación os presento el software que os permitirá manejar vuestra Webcam con Delphi. Primeramente tenéis que instalar en vuestro sis...



























