Customer Engagement
Adding Flutter dependency
Step 1: Ensure to complete basic setup for Smartech Base Flutter package
Go to Basic Setup to start integrating your Android project with Smartech Base Flutter package.
Step 2: Complete setup for Smartech Push Flutter package
Implement Smartech Push Flutter package in pubspecs.yaml
file under dependencies:
By using pub
smartech_base: ^3.5.0
smartech_push: ^3.5.0
smartech_appinbox: ^3.5.0
For Android SDK Setup
Step 1 : Define Latest SDK version
Add below line in gradle.properties
# Version of smartech push SDK to use with Flutter
SMARTECH_PUSH_SDK_VERSION=<<push_sdk_android_version>>
Step 2 : Integrate the latest Netcore CE SDK
Make the following changes in the app-level build.gradle
api "com.netcore.android:smartech-push:${SMARTECH_PUSH_SDK_VERSION}"
api "com.netcore.android:smartech-push:${SMARTECH_PUSH_SDK_VERSION}"
Step 3 : Initiate the Netcore CE SDK, Add below code in MyApplication.kt file
Also add SmartPush Notification Listener and function to render notification as below.
override fun onCreate() {
super.onCreate()
// Initialize Flutter Smartech Push Plugin
SmartechPushPlugin.initializePlugin(this)
}
override fun onCreate() {
super.onCreate()
SmartechPushPlugin.Companion.initializePlugin(this);
}
Step 4: Integrate Firebase Cloud Messaging in your app if customer wants to use native FCM
Please follow Google’s Documentation to set up native FCM integration in your app, if it is not already done.
Provide token via setDevicePushToken()
and notification payload via handlePushNotification()
methods to CE SDK. handlePushNotification()
method will only display a notification if the Notification payload originated from Netcore and will safely ignore if not. The code of the class should look similar to the following:
public class <YourFirebaseMessagingServiceClass> extends FirebaseMessagingService {
@Override
public void onNewToken(@NonNull String token) {
super.onNewToken(token);
SmartPush.getInstance(new WeakReference<Context>(this)).setDevicePushToken(token);
//<Your code>
}
@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
boolean isPnHanledBySmartech = SmartPush.getInstance(new WeakReference<Context>(context)).handleRemotePushNotification(remoteMessage);
if(!isPnHanledBySmartech){
// Notification from other sources, handle yourself
}
}
}
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onNewToken(token: String) {
super.onNewToken(token)
SmartPush.getInstance(WeakReference(this)).setDevicePushToken(token)
}
override fun onMessageReceived(message: RemoteMessage) {
super.onMessageReceived(message)
val isPnHanledBySmartech:Boolean = SmartPush.getInstance(WeakReference(context)).handleRemotePushNotification(remoteMessage))
if (!isPnHanledBySmartech){
// Notification from other sources, handle yourself
}
}
}
Caution
Write the following code in the
onCreate
function of the launcher activity of your application only if you are using SDk version older than 3.5.0.
new DeeplinkReceivers().onReceive(this, getIntent());
class MainActivity: FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
SmartechDeeplinkReceivers().onReceive(this, intent)
}
}
Step 5: Integrate flutter_firebase in Your App if Step-4 is not done and customer wants to use flutter firebase
Provide a token via setDevicePushToken()
and notification payload via handlePushNotification()
methods to Smartech Push Plugin. The handlePushNotification()
method will only display a notification if the notification payload originated from Netcore and will safely ignore it if not. The code of the class should look similar to the following:
- Set Device Push Token
final androidToken = await FirebaseMessaging.instance.getToken();
if (androidToken != null) {
SmartechPush().setDevicePushToken(androidToken);
}
- Send Push Notification Data from FCM to Smartech Plugin
// For foreground state
FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
bool isFromSmt = await SmartechPush().isNotificationFromSmartech(message.data.toString());
if(isFromSmt){
SmartechPush().handlePushNotification(message.data.toString());
return;
}
// handle if not from Smartech
});
// For background/terminated state
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
await Firebase.initializeApp();
bool isFromSmt = await SmartechPush().isNotificationFromSmartech(message.data.toString());
if(isFromSmt){
SmartechPush().handlePushNotification(message.data.toString());
return;
}
// handle if not from Smartech
}
Control Auto-Ask Notification Permission on Android 13
On Android 13 (API level 33) and above, the POST_NOTIFICATIONS
permission is required to publish notifications. The Smartech SDK requests notification permissions automatically upon initializing SmartPush SDK. However, best practices suggest asking for this permission after the user has engaged with the app for a while. Therefore, you can control whether the SDK asks for notification permissions automatically.
To disable the automatic notification permission request by the SmartPush SDK, add the following code to your AndroidManifest.xml:
<meta-data
android:name="SMT_IS_AUTO_ASK_NOTIFICATION_PERMISSION"
android:value="0" />
0
- Smart Push SDK will not ask for notification permission automatically. You must implement the notification permission request as described in step 9.1
- The Smart Push SDK will automatically ask for notification permissions. You do not need to handle this on the app side.
Notifications Permissions for Android 13 (API Level 33)
Android 13 and higher supports runtime permissions for sending notifications from an app using POST_NOTIFICATIONS
. This change helps users focus on the notifications that are most important to them. Refer to the official documentation for more details.
Smartech Push SDK version 3.2.16 and above supports the following APIs. When the application is running on Android 13, you need to request the user's notification permission to show notifications.
Steps for Applications Integrating Smartech Push SDK
- Notify SDK of Permission Request's Response: Once the application requests notification permission from the user, notify the SDK of the user’s response using the following API:
SmartechPush().updateNotificationPermission();
- Request Permission Prompt from Smartech SDK: Use the API below to show the user the permission request dialog. When using this API, the SDK automatically tracks the response, so you don't need to update the permission result manually. Add the following code in any
Activity's onCreate()
method where you want to show this permission prompt:
SmartechPush().requestNotificationPermission(MyNotificationPermissionCallback());
class MyNotificationPermissionCallback implements SMTNotificationPermissionCallback {
@override
void notificationPermissionStatus(int status) {
print('Permission status: $status');
}
}
Note
The above functions are available in Smartech Push SDK version 3.5.1 and above.
For iOS SDK Setup
Setting up Push Notifications for your iOS project is a quick 8 steps process
Ensure you have done the Basic Setup before you start integrating push notifications.
Step 1: Adding SmartPush SDK dependency - CocoaPods
- In the
Podfile
add theSmartPush-iOS-SDK
as a dependency.
pod 'SmartPush-iOS-SDK', '~> <<push_sdk_ios_version>>'
- Run the following command to update the added pod in your
Podfile
.
pod install
Once your installation is complete, you will have to open the workspace file (YOUR-PROJECT-NAME.xcworkspace) that is created.
- Import SmartPush SDK in AppDelegate class.
#import <SmartPush/SmartPush.h>
import SmartPush
Step 2: Adding & Configuring of Extensions
Click here to add & configure extensions.
Step 3: Register For Remote Notifications
To receive push notifications, you must send the device token you received using RegisterForRemoteNotificationsWithDeviceToken to the Netcore CE. Refer to the following code:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[[SmartPush sharedInstance] didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
SmartPush.sharedInstance().didRegisterForRemoteNotifications(withDeviceToken: deviceToken)
}
For an error/failure in registering remote notification.
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
[[SmartPush sharedInstance] didFailToRegisterForRemoteNotificationsWithError:error];
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
SmartPush.sharedInstance().didFailToRegisterForRemoteNotificationsWithError(error)
}
Step 4: Implementation of UNUserNotificationCenterDelegate methods
Implement the following code in delegate methods of UNUserNotificationCenter. First import following frameworks provided by apple for UNUserNotificationCenterDelegate
#import <UserNotifications/UserNotifications.h>
#import <UserNotificationsUI/UserNotificationsUI.h>
import UserNotifications
import UserNotificationsUI
Confirm UNUserNotificationCenterDelegate in AppDelegate class
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//....
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
//...
return YES;
}
//Confirming UNUserNotificationCenterDelegate protocol
@interface AppDelegate () <UNUserNotificationCenterDelegate>
@end
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//...
UNUserNotificationCenter.current().delegate = self
//...
return true
}
//Confirming UNUserNotificationCenterDelegate protocol
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
}
Implement UNUserNotificationCenterDelegate methods in AppDelegate class
#pragma mark - UNUserNotificationCenterDelegate Methods
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
[[SmartPush sharedInstance] willPresentForegroundNotification:notification];
completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
[[SmartPush sharedInstance] didReceiveNotificationResponse:response];
completionHandler();
}
//MARK:- UNUserNotificationCenterDelegate Methods
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
SmartPush.sharedInstance().willPresentForegroundNotification(notification)
completionHandler([.alert, .badge, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
SmartPush.sharedInstance().didReceive(response)
completionHandler()
}
Step 5: Set Notification Options
Netcore CE SDK has a default method that sets the notification options with options Sound, Alert, Badge. For that, you need to call the method registerForPushNotificationWithDefaultAuthorizationOptions in AppDelegate class.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//...
[[SmartPush sharedInstance] registerForPushNotificationWithDefaultAuthorizationOptions];
//...
return YES;
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//...
SmartPush.sharedInstance().registerForPushNotificationWithDefaultAuthorizationOptions()
//...
return true
}
If you want to change options you can use the following method named setNotificationOptions
to set the notification options in AppDelegate class in didFinishLaunchingWithOptions method.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//...
[[SmartPush sharedInstance] registerForPushNotificationWithAuthorizationOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound)];
//...
return YES;
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//...
SmartPush.sharedInstance().registerForPushNotification(authorizationOptions: [.alert, .badge, .sound])
//...
return true
}
Step 6:Retrieving Deeplink Data
#pragma mark - Smartech Delegate
- (void)handleDeeplinkActionWithURLString:(NSString *)deeplinkURLString andNotificationPayload:(NSDictionary *_Nullable)notificationPayload {
NSLog(@"SMTLogger: handleDeeplinkActionWithURLString passing notification data to base flutter plugin");
[SmartechBasePlugin handleDeeplinkAction:deeplinkURLString andCustomPayload:notificationPayload];
}
// MARK: - Smartech Delegate Methods
func handleDeeplinkAction(withURLString deeplinkURLString: String, andNotificationPayload notificationPayload: [AnyHashable : Any]?) {
print("SMTLogger: handleDeeplinkActionWithURLString passing notification data to base flutter plugin")
SmartechBasePlugin.handleDeeplinkAction(deeplinkURLString, andCustomPayload:notificationPayload)
}
Step 7: Configuring Capabilities of App
Enable the below app capabilities in the targets of your main app. (To know how to add capabilities check this developer document.)
- App Groups - Enable/Add and select a valid App Group for your app. This is used by App, Service Extension, and Content Extension to share data with each other. Make sure that you select the same App Group for App, Service Extension, and Content Extension.
- Background Modes - Enable/Add Background Modes and select Remote notifications. This allows the app to receive remote notifications in the background.
- Push Notifications - Enable/Add Push Notifications.
Step 8: Enable Push Notification for App Id
Configure App Push Notifications feature for your App ID in Apple Developer Account. Check this document for details.
Step 9: APNs key setup
Click here for steps to create APNs key.
Testing Push Notifications
- Add App Transport Security Settings with Allow Arbitrary Loads as YES in Info.plist of App, Service Extension, and Content Extension to support Http calls.
- Push Notifications can only be tested over a real device and NOT through XCode. You can use any iOS device (iPhone, iPad, iPod Touch) to test the push notifications.
Handling deeplink on Flutter
To Handle deeplink with exposing payload use below method in your main function. Use the below method if smartech_base
plugin version is >= 3.2.7
Smartech().onHandleDeeplink((String? smtDeeplinkSource, String? smtDeeplink, Map<dynamic, dynamic>? smtPayload, Map<dynamic, dynamic>? smtCustomPayload) async {
// Perform action on click of Notification
});
The below method will provide the deep link value and custom payload. Use the below method if smartech_base
plugin is < 3.2.7
Smartech().onHandleDeeplinkAction((String? link, Map<dynamic, dynamic>? map, bool? isAfterTerminated) async {
// Handle the deeplink action
});
Caution:
We also need to handle deeplink in the terminate state so add the below code inside the main.dart file or put inside the class called by your application only if you are on plugin version older than 3.5.0.
Smartech().onHandleDeeplinkActionBackground(); //method required for Android platform only
Updated about 2 months ago