PC SOFT

GRUPOS DE DISCUSSÃO PROFISSIONAL
WINDEVWEBDEV e WINDEV Mobile

Inicio → WINDEV 25 → Wx - Tutorial completo do recurso de PUSH (GCM) com Windev Mobile v.20 desenvolvido pelo sr Tom Silva e Adriano Boller para a comunidade Wx Brasil.
Wx - Tutorial completo do recurso de PUSH (GCM) com Windev Mobile v.20 desenvolvido pelo sr Tom Silva e Adriano Boller para a comunidade Wx Brasil.
Iniciado por adrianoboller, mar., 19 2016 6:46 PM - 12 respostas
Membro registado
3.651 mensagems
Popularité : +175 (223 votes)
Publicado em março, 19 2016 - 6:46 PM
Prezados,

Com muita satisfação e alegria, segue aqui nesse post Wx um Tutorial Completo, um passo a passo de como fazer funcionar o recurso de PUSH (GCM) em uma aplicação Android ou iOS usando a plataforma de desenvolvimento Windev Mobile versão 20.

Esse post foi feito com a parceria do desenvolvedor Wx o Sr. Tom Silva (Quito - Equador) Skype: tom.wcsdesigner e o distribuidor e representante oficial Pcsoft no Brasil o Sr. Adriano Boller (República de Curitiba - Paraná - Brasil) Skype: adrianoboller.

É um material desenvolvido para a língua portuguesa para a comunidade Wx do Brasil, mas pode ser traduzida para outras linguagens desde que ocorra um aviso prévio aos dois autores.

Esse material vem de encontro a diversas solicitações crescentes sobre esse assunto que é cada vez mais solicitado pelas empresas, um recurso de notificar os seus clientes de forma que mesmo estando com o aplicativo desligado, mas com o celular operante e com sinal 3g ou wifi receba uma notificação de um aplicativo servidor e reabra a aplicação e execute uma ação remota via uma mensagem usando uma palavra chave ou um aviso, ou acender o flash do celular, em fim a criatividade acaba sendo o mestre nesse tipo de projeto.

Endereço dos arquivos exemplos envolvidos nesse estudo:

C:\WinDev Mobile 20\Examples\Cross-platform\Push Mobile\






Usando o Windev Mobile abra esses dois projetos:

Android Push & iOS Push = Aplicações Cliente que recebem as mensagens Push = apk ou proj xcode


Usando o Windev ou o Webdev abra esse projeto de Webservice:

WD Push Server = Aplicação Middleware, ou seja Webservice, Tabela de repasse entre o Cliente e o Servidor = (wsdl):


Usando o Windev abra a aplicação exemplo abaixo de envio das mensagens:

WD Send Push = Aplicação server .Exe, responsável por ter o ID e o campo de envio da mensagem broadcast para as aplicações clientes mobile, esse Send Push é um executável, mas pode ser uma aplicação mobile ou um site e até mesmo um metodo de webservice = exe

--
Adriano José Boller
______________________________________________
Consultor e Representante Oficial da
PcSoft no Brasil
+55 (41) 9949 1800
adrianoboller@gmail.com
skype: adrianoboller
http://wxinformatica.blogspot.com.br/
Membro registado
3.651 mensagems
Popularité : +175 (223 votes)
Publicado em março, 19 2016 - 7:44 PM
Prezados

Segue aqui o download da pasta de exemplos citada acima:





https://mega.nz/…

--
Adriano José Boller
______________________________________________
Consultor e Representante Oficial da
PcSoft no Brasil
+55 (41) 9949 1800
adrianoboller@gmail.com
skype: adrianoboller
http://wxinformatica.blogspot.com.br/
Membro registado
3.651 mensagems
Popularité : +175 (223 votes)
Publicado em março, 19 2016 - 8:55 PM
Badge app icons













SysIconBadge (Função)
Em francês: SysIconeBadge

Retorna ou modifica o valor exibido no emblema associado com o ícone de um aplicativo.

http://help.windev.com/en-US/…

//Exemplo
// Aumenta o emblema para informar o usuário de um novo e-mail recebido
SysIconBadge ( SysIconBadge () + 1 )




TileDisplayBadge (Função)
Em francês: TuileAfficheBadge

http://help.windev.com/en-US/…

Exibe um emblema (notificação numérico ou imagem) na telha de uma aplicação de aplicativos Windows Store.

Por exemplo, a telha seguinte propõe uma notificação numérico que indica o número 12 e 12 que indica que as mensagens devem ser lidas.
http://help.windev.com/en-US/…





// Exemplo
TileDisplayBadge ( nNbUnreadEmails )


Inteiro de 0 a 99, o valor selecionado será exibido na telha. O valor 0 é usado para excluir o emblema .
Constante usado para exibir uma imagem em mosaico. Esta constante pode ser escolhido entre os seguintes valores:





--
Adriano José Boller
______________________________________________
Consultor e Representante Oficial da
PcSoft no Brasil
+55 (41) 9949 1800
adrianoboller@gmail.com
skype: adrianoboller
http://wxinformatica.blogspot.com.br/
Membro registado
3.651 mensagems
Popularité : +175 (223 votes)
Publicado em março, 19 2016 - 9:02 PM
Prezados,

Segue aqui o Push.doc em Português.









https://mega.nz/…

--
Adriano José Boller
______________________________________________
Consultor e Representante Oficial da
PcSoft no Brasil
+55 (41) 9949 1800
adrianoboller@gmail.com
skype: adrianoboller
http://wxinformatica.blogspot.com.br/
Membro registado
3.651 mensagems
Popularité : +175 (223 votes)
Publicado em março, 19 2016 - 9:32 PM
Membro registado
3.651 mensagems
Popularité : +175 (223 votes)
Publicado em março, 20 2016 - 1:35 AM
Prezados





Aqui segue o vídeo desenvolvido com o Tom Silva e o Adriano Boller sobre o recurso de Push usando os exemplos da Pcsoft.







:merci:

--
Adriano José Boller
______________________________________________
Consultor e Representante Oficial da
PcSoft no Brasil
+55 (41) 9949 1800
adrianoboller@gmail.com
skype: adrianoboller
http://wxinformatica.blogspot.com.br/
Membro registado
3.651 mensagems
Popularité : +175 (223 votes)
Publicado em abril, 05 2016 - 9:58 PM
Prezados,

Segue exemplo do sr Tiago Linhares (Várzea Grande, Brasil)

Push iOS - Apple, feito com exemplo Windev Mobile









Show de bola!

Parabéns!

:merci:

--
Adriano José Boller
______________________________________________
Consultor e Representante Oficial da
PcSoft no Brasil
+55 (41) 9949 1800
adrianoboller@gmail.com
skype: adrianoboller
http://wxinformatica.blogspot.com.br/
Membro registado
3.651 mensagems
Popularité : +175 (223 votes)
Publicado em dezembro, 10 2016 - 11:54 AM
Prezados,

Segue maiores detalhes:

https://www.dropbox.com/sh/04iq2y92lzdbeuo/AACBBMOa1-wUY42sXKEO6W7Va…

São 2 arquivos esclarecedores.

:merci:

--
Adriano José Boller
______________________________________________
Consultor e Representante Oficial da
PcSoft no Brasil
+55 (41) 9949 1800
adrianoboller@gmail.com
skype: adrianoboller
http://wxinformatica.com.br/
Membro registado
37 mensagems
Popularité : +5 (5 votes)
Publicado em maio, 30 2017 - 6:13 PM
Primeiro parabéns pelo tutorial em GCM, muito bom.
Porém estávamos para começar um projeto de desenvolvimento com um parceiro, e agora o GCM está descontinuado e foi substituído pelo Firebase.
Seria possível fazerem a atualização do Tutorial para Firebase.

Ou informar se a PC Soft tem atualização do exemplo com o uso de Firebase

Um abraço
Membro registado
3.651 mensagems
Popularité : +175 (223 votes)
Publicado em junho, 01 2017 - 9:50 PM
Bastiaan,

Discordo!

Nao deixou de existir.... ele evoluiu!!!

Tem os mesmos recursos e recursos adicionais....

Veja o que fala o site oficial: https://developers.google.com/cloud-messaging/

Firebase Cloud Messaging (FCM) is the new version of GCM. It inherits the reliable and scalable GCM infrastructure, plus new features! See the FAQ to learn more. If you are integrating messaging in a new app, start with FCM. GCM users are strongly recommended to upgrade to FCM, in order to benefit from new FCM features today and in the future.

em português:

O Firebase Cloud Messaging (FCM) é a nova versão do GCM. Ele herda a infra-estrutura GCM confiável e escalável, além de novos recursos! Veja as perguntas freqüentes para saber mais. Se você estiver integrando mensagens em um novo aplicativo, comece com o FCM. Os usuários do GCM são altamente recomendados para atualizar para o FCM, para se beneficiar dos novos recursos do FCM hoje e no futuro.

Em breve publico as mudanças usando o FCM ok

Mas como bom programador, é só fazer como eu, ficar lendo e estudando e tentando ate amanhecer o dia, até conseguir fazer funcionar.

Leia a documentação é simples:

https://developers.google.com/cloud-messaging/http-server-ref

https://developers.google.com/cloud-messaging/gcm

https://developers.google.com/cloud-messaging/samples

https://developers.google.com/cloud-messaging/support

é o caminho das pedras ok...

Eu faço o convite, para fazer o novo jeito de fazer usando FCM, é a melhor forma de aprender e fixar conteúdo, é fazer um tutorial sobre ele.

bons estudos...

:merci:

--
Adriano José Boller
______________________________________________
Consultor e Representante Oficial da
PcSoft no Brasil
+55 (41) 99949 1800
adrianoboller@gmail.com
skype: adrianoboller
http://wxinformatica.com.br/
Membro registado
3.651 mensagems
Popularité : +175 (223 votes)
Publicado em setembro, 13 2017 - 2:08 PM
Ordem de compilação

C:\WINDEV Mobile 22 US\Examples\Cross-platform\Push Mobile





O GCM mudou para Firebase mas é o mesmo procedimento, a técnica é a mesma.

Segue videos complementares sobre o assunto:

PUSH Android


PUSH iOS


Config PUSH Firebase Google










--
Adriano José Boller
______________________________________________
Consultor e Representante Oficial da
PcSoft no Brasil
+55 (41) 99949 1800
adrianoboller@gmail.com
skype: adrianoboller
http://wxinformatica.com.br/
Mensagem modificada, setembro, 13 2017 - 2:10 PM
Membro registado
3.651 mensagems
Popularité : +175 (223 votes)
Publicado em abril, 18 2018 - 7:47 PM
Versao nova
/////////////

PROJECT/ CODE/ INIT
////////////////////////
//Globais
Versao(1)

HModifyStructure("*",hmsBackgroundTask)

HCreationIfNotFound("*","48864")

//dsQRY is data source
//
//HExecuteSQLQuery(dsQRY,hQueryDefault, "SELECT 1 existe FROM t004_sessao_campanha WHERE t004_Codigo=8098")
//HReadFirst(dsQRY)
//Info(HFound(dsQRY), HNbRec(dsQRY))


gbCapturado is boolean = False

gnLoCodigoUsuario is int = 0

gnCaca, gnCampanha is int = 1

gnUserId is int = 0

gsPosicao is string

gloDebug is boolean = False

bLogin, gbLogado, gbAceite, gbThreadFim, gbSplash, gbOpenMeusDados, gbThreadUmaVez, GloLimpar, gbPause is boolean = False

GloUserId, GloNome, GloEmpresa, GloMatricula, GloSenha, GloCpf, gloStatus, gloStatusMessage, GloTextoDistancia, GloSaldoDataAtualizacao, GloEmail, GloSms, GloCelular are string = ""

grlatitude, grlongitude, grCurrentLatitude, grCurrentLongitude, grDistance is real

gloMinhaPosicao is geoPosition

gloLojaPosicao is geoPosition

gloLojaMaisProxima is geoPosition

MarkerLoja,MarkerCliente is Marker

gloMarca, gloModelo, gloVersao is string

gloResWidth, gloResHeigth, gloEtapa is int

gbufPushId is Buffer

gloSessaoData, gloProdutosData, gloMidiasData, gloNotificacaoData are string

//ent
gsImei is string

gsMacAddress is string

ent is a entrada // token de login de entrada

MSG_Aguarde is string = "Conteúdo está sendo carregado..."



////////////////////////////////////////////////////////////////////////////////////////////////
// Import the addresse of your Web service into WINDEV Mobile (WD Push Server example)
////////////////////////////////////////////////////////////////////////////////////////////////



<Compile IF Configuration="Android application">
// Enables the push notifications
NotifPushEnable(ActivatePushNotify) /// json - gooo //// gooo ----ret

// Callback for calling the notifications
NotifPushProcedure(ReceivePushNotify)
<END>


<Compile IF Configuration="iOS application">
// Callback for calling the notifications
NotifPushProcedure(ReceivePushNotify)

IF ExeInfo(exeLaunch) <> exePushNotification THEN
// Enables the push notifications
NotifPushEnable(ActivatePushNotify)
END
<END>


//PUSH

// Global variables
gsNamePersistentThread is string = "PersistentNotifications"
gsPeriodicityPreference is string = "periodicity"
gsPreferenceNotificationsEnabled is string = "benabled"
gbActive is boolean = False
gnPeriodicity is int

//PERSISTENTE
gPersistentNotification is a Notification
<Compile IF Configuration="Android application">
gPersistentNotification..ActivateApplication = True
gPersistentNotification..Title = "Persistent notifications"
<END>
gPersistentNotification..Message = "Persistent notifications enabled"
gPersistentNotification..Icon = "notif_persistent.png"
gPersistentNotification..Sound = "notif.mp3"

//ESPORADICO
gSporadicNotification is a Notification
<Compile IF Configuration="Android application">
gSporadicNotification..ActivateApplication = True
gSporadicNotification..Deletable = True
<END>
gSporadicNotification..Icon = "notif.png"
gSporadicNotification..Sound = "notif.mp3"

gbDebug is boolean = False // Simular entrada rápida
gbClear is boolean = False // Forçar limpeza do banco

IF InSimulatorMode() AND gbDebug THEN
ent.IMEI = "123456789012345784"
ent.UserId = 53156
ent.AccessToken = "CF44A2A4-CD33-4AF2-99E5-7D89A8974229"
ent.device.marca = "Teste"
ent.device.modelo = "Teste"
ent.device.versao = "1"

gbLogado = True

OpenMobileWindow(WIN_02_MeusDados)
END



PROCEDURES GLOBAIS
//////////////////////////

// Summary: <specify the procedure action>
// Syntax:
//ActivatePushApplications (<bActivate> is boolean)
//
// Parameters:
// bActivate (boolean): <specify the role of bActivate>
// Return Value:
// None
//
// For instance:
// Indicate an example.
//
Procedure ActivatePushApplications(bActivate is boolean)



IF bActivate THEN
// Enable the notifications
gbActive = True

SaveParameter(gsPreferenceNotificationsEnabled,True)

IF ThreadState(gsNamePersistentThread) = threadUnknown THEN
ThreadExecute(gsNamePersistentThread,threadGlobalContext,ManageNotifications)
<Compile IF Configuration="Android application">
ThreadPersistent(gsNamePersistentThread,gPersistentNotification)
<END>
ELSE
// The notifications are already enabled
END
ELSE
// Disable the notifications
gbActive = False
SaveParameter(gsPreferenceNotificationsEnabled,False)
NotifDelete(gSporadicNotification)
END

// Refreshes the status
RefreshStatus()



// Summary: Callback called after registration toward the service of iOS notifications
// Syntax:
//ActivatePushNotify (<bufIdentifier> is buffer, <sError> is string)
//
// Parameters:
// bufIdentifier (buffer): Identifier to store on the server
// sError (UNICODE string): <specify the role of sError>

Procedure ActivatePushNotify(bufIdentifier is Buffer, sError is string)

Empresa, Matricula, Senha, User, nImei, Celular is string

FOR EACH t001_usuarios

IF HFound(t001_usuarios) = True AND t001_usuarios.t001_nome <> "" THEN

Empresa = t001_usuarios.t001_empresa
Matricula = t001_usuarios.t001_matricula
Senha = t001_usuarios.t001_senha
User = t001_usuarios.t001_nome
nImei = t001_usuarios.t001_imei
Celular = t001_usuarios.t001_celular_marca +" - "+ t001_usuarios.t001_celular_modelo

END

END

HReadSeekFirst(t016_pushId,PushIdentifierID,1,hKeepFilter)

t016_pushId.ServiceIdentifier = bufIdentifier

<Compile IF Configuration="Android application">
t016_pushId.ServiceType = 1 //google
<END>

<Compile IF Configuration="iOS application">
t016_pushId.ServiceType = 2 //apple
<END>

t016_pushId.PushIdentifierID = 1
t016_pushId.Imei = nImei
t016_pushId.User = User
t016_pushId.Empresa = Empresa
t016_pushId.Matricula = Matricula
t016_pushId.Senha = Senha
t016_pushId.MarcaModeloCelular = Celular

nTamanho is int = Length(bufIdentifier)

INIWrite("PUSH","ID",bufIdentifier,"push.ini")

gbufPushId = bufIdentifier

//PushIdString is string = BufferToHexa(sPushTxt, 4, BigEndian)

sPushTxt is string = INIRead("PUSH","ID","","push.ini")

PushIdString is string = BufferToHexa(sPushTxt, 1, BigEndian)

//Info("Lido do buf hexa: ",PushIdString)

t016_pushId.CustomInfo = PushIdString + " - Erro: " + sError

//info(tamanho,bufIdentifier)

IF HNbRec(t016_pushId) = 0 THEN

HAdd(t016_pushId)

ELSE

HModify(t016_pushId)

END



// Summary: <specify the procedure action>
// Syntax:
//DisplayNotification ()
//
// Parameters:
// None
// Return Value:
// None
//
// For instance:
// Indicate an example.
//
//
Procedure DisplayNotification()

sTime is string = TimeToString(TimeSys(),"HH:MM:SS")

NotifDelete(gSporadicNotification)

gSporadicNotification..Message = StringBuild("It is %1",sTime)
//gSporadicNotification..DropDownText = sTime
//gSporadicNotification..Title = sTime

NotifAdd(gSporadicNotification)



// Summary: <specify the procedure action>
Procedure ManageNotifications()

WHILE gbActive
// Displays the notification
DisplayNotification()

// Wait during the periodicity
ChronoStart(1)
WHILE gbActive _AND_ ((ChronoValue(1) / 1000) < gnPeriodicity)
Multitask(50)
END
ChronoEnd(1)
END



// Summary: Callback called when receiving a PUSH notification
// Syntax:
//ReceivePushNotify (<myNotify> is Notification)
//
// Parameters:
// myNotify (Notification): Notification that was received

Procedure ReceivePushNotify(myNotify is a Notification)

///csv

t015_push.t015_Content = myNotify..Content
t015_push.t015_ActionClick = myNotify..ActionClick
t015_push.t015_Icon_01 = myNotify..Icon
t015_push.t015_Message = myNotify..Message
t015_push.t015_Sound_01 = myNotify..Sound

<Compile IF Configuration="Android application">
t015_push.t015_ActivateApplication = myNotify..ActivateApplication
t015_push.t015_Chronometer = myNotify..Chronometer
t015_push.t015_ColorLED = myNotify..ColorLED
t015_push.t015_Deletable = myNotify..Deletable
t015_push.t015_DisplayLED = myNotify..DisplayLED
t015_push.t015_DropDownText = myNotify..DropDownText
t015_push.t015_LargeIcon_01 = myNotify..LargeIcon
t015_push.t015_Local = myNotify..Local
t015_push.t015_Priority = myNotify..Priority
t015_push.t015_Title = myNotify..Title
t015_push.t015_SecondaryMessage = myNotify..SecondaryMessage
t015_push.t015_Vibration = myNotify..Vibration
<END>

<Compile IF Configuration="iOS application">
myNotify..Badge = 1
<END>

t015_push.t015_Executou = False
t015_push.t015_datahora = DateSys() + TimeSys()

HAdd(t015_push)

Info(StringBuild("Notification received with ""%1"" as message and ""%2"" as content" , myNotify..Message,myNotify..Content))

// ex: If the content is the identifier of a product, you can display the corresponding product:



// Summary: <specify the procedure action>
// Syntax:
//[ <Result> = ] RefreshStatus ()
//
// Parameters:
// None
// Return Value:
// boolean: // None
//
// For instance:
// Indicate an example.
//
Procedure RefreshStatus()

IF LoadParameter(gsPreferenceNotificationsEnabled,False) THEN
gbActive = True
ELSE
gbActive = False
END

RESULT(gbActive)



CRIE NO GOOGLE A SUA CREDENCIAL QUE É UM ARQUIVO JSON E NO WIZARD DE DEPLOY/COMPILACAO VOCE VAI USAR ESSE JSON

NECESSARIO TER A CONTA NO GOOGLE CONSOLE

LOCAL DOS EXEMPLOS

C:\WINDEV Mobile 22\Examples\Cross-platform\Push Mobile

Lembro que o buffer vindo de cadastrono firebase quando vc abre a primeira vez O PROJETO no celular vc recebe o id e deve guardar esse id binario e registrar no seu banco de dados remoto no servidor para um dia se precisar poder mandar somente para aquela pessoa uma mensagemque sera atrelado ao cadastro com o termo de aceita o uso do aplicativo.

Quando desinstalar o app o id buffer vindo do google firebase sera desativadoe na reinstalacao sera criado um novo id

Você devera atualizar o seu webservice quando ele aceitar novamente os termos de uso do aplicativo enviando o cadastro com os mesmos dados.

E para transportar esse binário e mando via hexadecimal para conseguir transportar no xml ou no json.

Um forte abraço a todos!!!

--
Adriano José Boller
______________________________________________
Consultor e Representante Oficial da
PcSoft no Brasil
+55 (41) 99949 1800
adrianoboller@gmail.com
skype: adrianoboller
http://wxinformatica.com.br/
Mensagem modificada, abril, 18 2018 - 9:23 PM
Membro registado
498 mensagems
Popularité : +8 (8 votes)
Publicado em abril, 20 2018 - 9:41 PM
Olá Boller

Não é necessário usar o Web Service para enviar o Identificador do aplicativo, basta salvá-lo no banco de dados, a menos que você o use apenas para segurança.

mas em resumo não é tão necessário.

Atenciosamente,
José