Delphi android push уведомления

Создание постоянного Android Notification

Notification Уведомления в Android
Попробую изложить корректно, но готовьтесь к ужасу.. Заранее извините(( На просторах интернета.

Иконки Notification в Android 5
Столкнулся с проблей отображения иконки уведомления в статус баре на лолипоп 5. Я узнал, что.

Создание Push notification сервера и реализация работы
Народ кто может описать подробно и по русски как правильно подойти к вопросу push. Если лепить свой.

Вместо значка «белый квадратик» при вызове Notification в Android 5.0
при вызове уведомления вместо заданной иконки в системном трее «белый квадратик» те как положено.

Создание постоянного соединения с удаленным сервером
Суть вопроса в том как реализовать схему клиент-сервер. (сервер удаленный) задача такая: 1.

Создание приложения на Android
Решил заняться созданием программ для Android платформы. Опыт в программирование имеется, но тут.

Создание файла на Android
Есть небольшое приложение, которое должно сохранять в .txt (Можно использовать и другой, если он.

Создание эмулятора Android
Доброго времени суток. Когда создаю эмулятор в Android Virtual Device Manage и запускаю его.

Создание приложения на Android
Здравствуйте, решил попробовать написать приложения на Android на Delphi XE5, но столкнулся с такой.

Создание конфигурации на Android из 1C 8.3.2
Здравствуйте! Надежда только на этот форум осталась. Суть вопроса в чем: Есть пример создания.

Источник

FMX Developer

Маленький блог посвященный кроссплатформенной разработке на FMX под Android/IOS/Windows/MacOS

Translate

пятница, 24 февраля 2017 г.

Настройка пуш уведомлении через сервис Firebase для ANDROID и IOS [часть 2]

Доброго времени суток!

В предыдущей части, я рассказывал как сделать настройку пуш уведомления в консоли Firebase, в этой я покажу код на Delphi и серверную часть на PHP

Настройка FMX проекта

ANDROID

Delphi код

C++ Builder код

PHP код

Как правильно сохранять токен в БД?

Создаём нашу табличку чтобы хранить токены

CREATE TABLE PushTokens (
id int (11) AUTO_INCREMENT,
deviceID varchar(255) NOT NULL,
deviceToken varchar(511) NOT NULL,
platform varchar(11) NOT NULL,
PRIMARY KEY (id),
CONSTRAINT unq_deviceID UNIQUE (`deviceID`(100))
);

В таблице поле deviceID сделано уникальным, чтобы не допускать дублирование токенов

$sql = «INSERT INTO PushTokens (`deviceToken`, `deviceID`, `platform`) VALUE (‘$deviceToken’, ‘$deviceID’, ‘$platform’) ON DUPLICATE KEY UPDATE `deviceToken` = ‘$deviceToken'»;

Это особенность FMX, в нативной реализации проверяется наличие полей message и title, а с консоли они не приходят (но можно заполнить расширенные настройки и указать эти поля)

Как сделать многострочный текст в уведомлениях на Android?
Решение для Seattle/Berlin

26 комментариев :

Вроде статья не старая, но делали для iPhone уведомления, токены с iOs работают без apns2fcmToken и уведомления приходят.
Правда есть странность в гугле, что какой токен ему не подсунь в pushSend возвращается в success: количество , даже если заведомо несуществующий токен написать.

не подтвержаю, приходит failure с количеством недействительных токенов. даже если токен был валиден и срок его годности прошел, все равно придёт ошибка

Да точно, методом тыка проверил, но если а начале токена, до двоеточий, что-то написать, то токен все равно проходит. например токен «dlMLBXkg6lg:APA91bGPF3», и если его изменить на «111dlMLBXkg6lg:APA91bGPF3» то он также сработает, видимо эта часть до двоеточий для чего-то другого нужна ))

В своем проекте столкнулся со сложностями.
Исторически сложилось, что мое приложение для iOS и Android-платформ имеет разные идентификаторы пакетов (com.yourapp.PLATFORM).
В моем случае не получилось на FireBase собрать их в один пакет: сообщения до устройств Android доходили без проблем; iOS ни в какую не отрабатывал (несмотря на успешные сообщения об отправке со стороны Firebase <"multicast_id":7125252680403741812,"success":1,"failure":0,"canonical_ids":0,"results":[<"message_id":"0:1490294673113408%91729e8c91729e8c">]>
). Проблема с отправкой была не только при использовании php-скрипта, но и при попытках отправки через консоль Firebase. Даже при посыле на все iOS-устройства (без указания каких-либо конкретных токенов).
Проблема в конце-концов решилась заведением под iOS отдельного проекта в Firebase, получении своего Server key.

Читайте также:  Group speed dial для firefox android

Sorry, not working. ADeviceID comes up correctly, but AdeviceToken comes up blank. I use Delphi 10.2 Tokyo. I have this message to try get the Token: raised exception class EJNIException with message ‘java.io.IOException: MAIN_THREAD’.

This is a bug in Tokyo, you need to write in QC

Источник

Delphi android push уведомления

Copy raw contents

Copy raw contents

Receiving push notifications from Apple’s Push Notification and Google’s Firebase Cloud Messaging services

In the previous article we demonstrated how to roll your own Google Firebase Cloud Messaging and Apple APNS push notifications from Delphi apps in a unified manner. This article continues the conversation about how to easily receive and consume them in your Delphi mobile app.

If you are authoring a Delphi service for the cloud, you may have the need to send and receive push notifications from your service to your mobile client application. You could use an existing BAAS provider to accomplish this, but why pay for this when you can roll your own so easily with Delphi?

Delphi provides a base set of classes in the units FMX.PushNotification.Android and FMX.PushNotification.iOS that do most of the heavy lifting and allow you to easily consume remote push notifications. In this conversation we will be demonstrating a helper class that unifies the approach for both platforms, uses TMessage callbacks for notifications and device token changes and adds some new missing features.

For more information about us, our support and services visit the Grijjy homepage or the Grijjy developers blog.

The example contained here depends upon part of our Grijjy Foundation library.

Getting started on iOS

To receive push notifications on iOS you must:

Already have created an Apple Push Services certificate in the Apple Developer website for use in sending remote push notifications.

Create an App ID on the Apple Developer website for your project.

Enable Push Notifications for your App ID on the Apple Developer website for your project.

A Provisioning Profile must exist on the Apple website that matches the identifier.

Then in your Delphi Project Options you must set your CFBundleIdentifier for iOS build configurations to the matching name of the ID in Apple Developer website. (ex: com.some.app) This is the only thing your app will need to identify itself for Apple Push Notifications.

Getting started on Android

To receive push notifications on Android you must:

Obtain a Firebase Cloud Messaging API Key by setting up cloud messaging on Google’s developer site. This is also called the Server API Key under Firebase Cloud Messaging.

Modify your AndroidManifest.xml to register an Intent and add the following receiver:

For Android, we only need the Firebase Cloud Messaging API Key for our Delphi app.

The TgoRemotePushReceiver class unifies the receiving of remote push notifications from both APNS and Firebase Cloud Messaging into a common class model.

When you receive a remote push notification message from Android or iOS, the following TMessage is fired:

Since we are receiving a JSON payload for both Android and iOS we can examine the content here. This is useful is we want to include our own custom content in the payload that is app specific. See our article on sending remote push notifications for a discussion about customizing the payload.

If your device token changes on Android or iOS, the following TMessage is fired:

The above message is fired initially when you device token is assigned after app startup. Due to the variances in the way device tokens are handled on iOS and Android this event could be immediate or delayed by the operating system.

As a developer you should also be prepared that the device token could change if your application is reinstalled, the operating system is updated as well as dynamically while your app is active.

Читайте также:  Server side android app

Apple APNS quirks

On iOS Remote Push notification events are received only when your application is in the foreground or background. If your application is «force quit» also known as «terminated» then you cannot receive remote push notification events into your app. Instead when the push notification arrives on screen and is pressed your app is launched but without receiving a notification event.

Note: You only receive a single remote notification event at a time, meaning that if there are several events queued, the only one you receive is the one that the user clicked on in the iOS user interface.

iOS 8.x introduces a new approach called the PushKit which has the ability to silently launch your app into the background state. We will explore this in a future article.

Hello World for push notifications

To get started using the helper class, you will need your Android API Key for Firebase Cloud Messaging.

To subscribe to remote push notifications:

You will receive an Activated set to True if the notification is the likely result of a end-user actually pressing the notification.

To subscribe to device token changes:

Make sure you unsubscribe all the various TMessage listeners when you are completed.

Receiving remote push notifications in Delphi apps for Android and iOS is relatively straightforward with this helper class. In the end, all you need to know is the device token in order to send a message to a device.

Источник

Delphi android push уведомления

Sending iOS (and Android) remote push notifications from your Delphi service with the HTTP/2 protocol

In this article we are going to discuss how to make a base unifying class for sending remote push notifications from your service to both the iOS (Apple Push Notification Service) and Android (Firebase Cloud Messaging) as well as covering how to use the newer Apple HTTP/2 protocol interface for sending push notifications from Delphi.

If you are authoring a Delphi service for the cloud, you may have the need to send push notifications from your service to your client application. There are various ways to accomplish this including using third-party BAAS providers or rolling your own interface with some of the established libraries.

In the past Apple used a custom TCP binary protocol to send messages to the APNS. This was cumbersome and inflexible and had numerous pitfalls in determining whether your message was actually accepted by the interface. Apple recently released a newer interface that uses HTTP/2. The nice thing about this interface is, just like FCM it utilizes JSON for the payload of the protocol. However, the protocol uses the newer HTTP/2 protocol and ALPN (Application-Layer Protocol Negotiation Extension, defined in RFC 7301) which is required in your SSL handshake.

One other advantage, Apple also increased the maximium size of the payload from 2K to 4K with the new HTTP/2 interface as of iOS 9 devices.

We will show how to combine the Grijjy scalable client socket library with the excellent nghttp2 to solve both of these issues and transparently send push notifications to either Apple’s APNS or Google’s FCM from your Delphi service.

For more information about us, our support and services visit the Grijjy homepage or the Grijjy developers blog.

The example contained here depends upon part of our Grijjy Foundation library.

The source code and related example repository is hosted on GitHub at https://github.com/grijjy/DelphiRemotePushSender.

Nghttp2 is a fairly established library for implementing the HTTP/2 protocol. It handles all the compression and bitstreaming for implementing HTTP/2.

The HTTP/2 protocol and its header compression are rather complex and evolving so it is probably best not to try and implement this ourselves.

One of the great things about nghttp2 is you can utilize it entirely with memory buffers so it is a good match for our own scalable client socket classes for Windows and Linux. This way we get the benefit of HTTP/2 but we don’t have to rely on another implementation of sockets for scaling up our service.

Читайте также:  Восстановление резервной копии андроид с гугл диска

If you want to build the nghttp2 library for Windows to use in your Delphi application you will need to download the latest source. To build you can use Visual Studio or just download the Visual Studio Build Tools. You will also need to download and install CMAKE.

  1. Download the latest nghttp2 source from https://github.com/nghttp2/nghttp2
  2. Install CMAKE and the Build Tools for Visual Studio.
  3. Run CMAKE followed by a period cmake .
  4. Run CMAKE to build the release version cmake —build . —config RELEASE

Delphi header translation

Once completed you will have a nghttp2.dll. We will need our conversion for the header file for Delphi so we can use the nghttp2 methods directly.

Apple APNS & iOS Prerequisites

To use the TgoRemotePushSender class with Apple’s Push Notification Service, we need to create a certificate and convert that certificate into 2 PEM files, one for the certificate and one the private key.

There are quite a few primers on the Internet about how to create APNS certificates, so we will be brief here as it applies to our TgoRemotePushSender class.

On iOS you must create a production certificate that is universal by selecting the option «Apple Push Notification service SSL (Sandbox & Production)» under Certificates in the developer portal. This certificate must be matched with the proper AppId.

You need to download and install the certificate into the Mac OSX Keychain.

You need to export the Apple Push Notification service certificate and private key as 2 separate files (cert.p12 and key.p12) from the Keychain application on OSX. These can only be exported as .p12 files from the Keychain application.

To create PEM files we recommend using the OpenSSL binaries to convert as follows:

To remove the password from the APNS-key-password.pem file:

To test the certificate against the APNS interface to see if it works:

To use the TgoRemotePushSender class we need to know the Device Token for the target user’s device. You pass this value to the TgoRemotePushSender.Send method when sending your remote push notification. This is true of both iOS and Android targets.

For Android you also need to specify the TgoRemotePushSender.AndroidAPIKey . You can obtain an API Key by setting up cloud messaging on Google’s developer site. This is also called the Server API Key under Firebase Cloud Messaging.

For iOS you need to specify the TgoRemotePushSender.APNSKey which is essentially your Bundle Identifier (ex: com.mycool.app). You also need to apply the APNS certificate and private key .PEM files you previously created.

The structure of the class is fairly straightforward. To send a remote push notification, call the Send method and provide the DeviceToken and also the Title and Message body for the payload.

Note: You should create and reuse an instance of this class to avoid creating multiple connections to the push notification host. One model would be to perform notifications in batches based upon time. Apple warns about creating too many connections as a reason for blocking your service.

An example application demonstrating how to use this class is available within our repository on GitHub.

Sending custom user data

Now that both Apple and Google use JSON as their payload format, you can easily add your own custom JSON fields to the payload that are consistent with both platforms. While we don’t expose this directly in our class you can add additional content by simply expanding the JSON with your extra custom data.

TgoRemotePushSender and DelphiRemotePushSender are licensed under the Simplified BSD License. See License.txt for details.

About

Sending iOS (and Android) remote push notifications for your Delphi service with the HTTP/2 protocol

Источник

Оцените статью