แชร์ผ่าน


การรับการแจ้งเตือนแบบพุชบนอุปกรณ์เคลื่อนที่

หากต้องการเรียนรู้เพิ่มเติมเกี่ยวกับวิธีการโดยรวมในการตั้งค่าการแจ้งเตือนแบบพุชใน Customer Insights - Journeys โปรดไปที่ ภาพรวมการตั้งค่าการแจ้งเตือนแบบพุช

หากต้องการเปิดใช้งานการแจ้งเตือนแบบพุชใน Customer Insights - Journeys คุณต้องทำตามขั้นตอนต่อไปนี้:

  1. การกำหนดค่าแอปพลิเคชันการแจ้งเตือนแบบพุช
  2. การแมปผู้ใช้สำหรับการแจ้งเตือนแบบพุช
  3. การลงทะเบียนอุปกรณ์สำหรับการแจ้งเตือนแบบพุช
  4. การรับการแจ้งเตือนแบบพุชบนอุปกรณ์เคลื่อนที่
  5. การรายงานการโต้ตอบสำหรับการแจ้งเตือนแบบพุช

สำคัญ

เมื่อต้องการติดตามลิงก์ที่ผู้รับเปิดในการแจ้งเตือน คุณต้องรวบรวมความยินยอมในการติดตามลูกค้า เรียนรู้เพิ่มเติมเกี่ยวกับกลยุทธ์ในการรวบรวมความยินยอมของลูกค้าใน Customer Insights - Journeys: ภาพรวมการจัดการความยินยอม

หากคุณไม่ได้รวบรวมความยินยอมในการติดตาม คุณต้องใช้ฟิลด์ OriginalLink URL ที่อธิบายไว้ในส่วนย่อยของโค้ดด้านล่าง หากคุณได้รับความยินยอม คุณสามารถใช้ค่าฟิลด์ ลิงก์ ซึ่งสามารถติดตามได้

PushLinkClicked จะถูกสร้างโดยอัตโนมัติ URL คือลิงก์เปลี่ยนเส้นทางซึ่งสร้างการโต้ตอบหากใช้ลิงก์จากฟิลด์ ลิงก์

รับการแจ้งเตือนข้อความแบบพุชใน iOS

1. ตัวอย่างส่วนย่อยของโค้ดเพื่อแยกวิเคราะห์การแจ้งเตือนขาเข้าใน iOS:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{

// Print full message
    NSString *urlString = [[userInfo valueForKey:@"data"] valueForKey:@"link"];
    NSString *originalUrlString = [[userInfo valueForKey:@"data"] valueForKey:@"originalLink"];
    NSString *trackingIdString = [[userInfo valueForKey:@"data"] valueForKey:@"trackingId"];
    
    if(![urlString isEqual:[NSNull null]])
    {
        if([urlString length] != 0)
        {
            [self createInteraction:[NSNumber numberWithInt:0] stringTracking:trackingIdString];
            
            NSURL *url = [NSURL URLWithString:urlString];
            if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10) {
                
// iOS 10 and above
                [[UIApplication sharedApplication] openURL:url options:[NSDictionary dictionary] completionHandler:nil];
            }
            else
            {
                [[UIApplication sharedApplication] openURL:url]; // iOS <10
            }
        }
    }
    else
    {
        [self createInteraction:[NSNumber numberWithInt:1] stringTracking:trackingIdString];
    }
}

ตัวอย่างส่วนย่อยของโค้ดเพื่อแยกวิเคราะห์การแจ้งเตือนขาเข้าใน iOS (เวอร์ชัน Swift):

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse,  withCompletionHandler completionHandler: @escaping () -> Void) { 

        let userInfo = response.notification.request.content.userInfo 
        let data = userInfo["data"] as? [String:Any] ?? [:]; 
        print("User info \(userInfo)") 
        let urlString = data["link"] as? String; 
        let trackingIdString = data["trackingId"] as? String; 

        if(urlString != nil && !urlString!.isEmpty) 
        { 

            self.createInteraction(typeInteraction:0, trackingId:trackingIdString ?? ""); 

            if let url = URL(string: urlString ?? ""), UIApplication.shared.canOpenURL(url) { 

                UIApplication.shared.open(url) 
            } 
        } 
        else 
        { 
            self.createInteraction(typeInteraction:1, trackingId:trackingIdString ?? ""); 
        } 
        // Always call the completion handler when done. 
        completionHandler() 
    } 

2. ตัวอย่างส่วนย่อยของโค้ด Swift เพื่อแยกวิเคราะห์การแจ้งเตือนแบบพุชแบบผสมที่เข้ามาใน iOS (การแจ้งเตือนพร้อมรูปภาพ):

นอกเหนือจากวิธีการ didReceive ใน AppDelegate เราจำเป็นต้องเพิ่ม NotificationExtension เพื่อสกัดกั้นการแจ้งเตือนก่อนที่จะแสดง ดาวน์โหลดรูปภาพ และเพิ่มข้อมูลการแจ้งเตือนด้วยข้อมูลรูปภาพ เรียนรู้เพิ่มเติม: UNNotificationServiceExtension

class NotificationService: UNNotificationServiceExtension { 
    var contentHandler: ((UNNotificationContent) -> Void)? 
    var content: UNMutableNotificationContent? 
    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { 
        self.contentHandler = contentHandler 
        self.content        = (request.content.mutableCopy() as? UNMutableNotificationContent) 
        if let bca = self.content { 
            func save(_ identifier: String, 
                      data: Data, options: [AnyHashable: Any]?) -> UNNotificationAttachment? { 
                    let directory = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(ProcessInfo.processInfo.globallyUniqueString, isDirectory: true) 
                    do { 
                        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil) 
                        let fileURL = directory.appendingPathComponent(identifier) 
                        try data.write(to: fileURL, options: []) 
                        return try UNNotificationAttachment.init(identifier: identifier, url: fileURL, options: options) 
                    } catch {} 
                    return nil 
            } 
            func exitGracefully(_ reason: String = "") { 
                let bca    = request.content.mutableCopy() as? UNMutableNotificationContent 
                bca!.title = reason 
                contentHandler(bca!) 
            }
            DispatchQueue.main.async { 
                guard let content = (request.content.mutableCopy() as? UNMutableNotificationContent) else { 
                    return exitGracefully() 
                } 
                let userInfo : [AnyHashable: Any] = request.content.userInfo; 
                let data = userInfo["data"] as? [String:Any] ?? [:]; 
                guard let attachmentURL = data["imageUrl"] as? String else { 
                    return exitGracefully() 
                } 
                guard let imageData = try? Data(contentsOf: URL(string: attachmentURL)!) else { 
                    return exitGracefully() 
                } 
                guard let attachment = save("image.png", data: imageData, options: nil) else { 
                    return exitGracefully() 
                } 
                content.attachments = [attachment] 
                contentHandler(content) 
            } 
        } 
    }   
    override func serviceExtensionTimeWillExpire() { 
        // Called just before the extension will be terminated by the system. 
        // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. 
        if let contentHandler = contentHandler, let bestAttemptContent =  content { 
            contentHandler(bestAttemptContent) 
        } 
    } 
}

รับการแจ้งเตือนใน Android

ตัวอย่างส่วนย่อยของโค้ดเพื่อแยกวิเคราะห์การแจ้งเตือนขาเข้าใน Android

ส่วนที่ 1: การรับรหัสติดตามจากข้อความแจ้งเตือน

หมายเหตุ

Customer Insights - Journeys ใช้รูปแบบข้อความข้อมูลแทนรูปแบบการแจ้งเตือน ตัวเวลือกนี้ต้องการให้แอปไคลเอ็นต์แยกวิเคราะห์เพย์โหลดข้อมูลที่ส่งโดย Customer Insights - Journeys เพื่อแยกลิงก์ที่ถูกต้อง (ติดตามหรือไม่ได้ติดตาม) เรียนรู้เพิ่มเติม: เกี่ยวกับข้อความ FCM

แทนที่วิธีการ OnMessageReceived ของ FirebaseMessagingService และแยกข้อมูลที่ต้องการออกจากเพย์โหลดดังที่แสดง:

@Override 
    public void onMessageReceived(RemoteMessage remoteMessage) { 
         
// Not getting messages here? See why this may be: https://goo.gl/39bRNJ 
        Log.d(TAG, "From: " + remoteMessage.getFrom()); 
        String message = null; 
        String title = null; 
        String deepLink = null; 
        String name = null; 
        String trackingId = null; 

        String imageUrl = null; 
         
// Check if message contains a notification payload. 
        if (remoteMessage.getNotification() != null) { 
            message = remoteMessage.getNotification().getBody(); 
            title = remoteMessage.getNotification().getTitle(); 
        } 
         
// Check if message contains a data payload. 
        if (remoteMessage.getData().size() > 0) { 
            if (remoteMessage.getData().get("title") != null) { 
                title = remoteMessage.getData().get("title"); 
            } 
            if (remoteMessage.getData().get("body") != null) { 
                message = remoteMessage.getData().get("body"); 
            } 

if (remoteMessage.getData().get("imageUrl") != null) { 
    imageUrl = remoteMessage.getData().get("imageUrl"); 
} 

// If tracking consent has been taken, use link otherwise use 'originalLink' 
            if (remoteMessage.getData().get("link") != null) { 
                deepLink = remoteMessage.getData().get("link"); 
            } 
            if (remoteMessage.getData().containsKey("trackingId")) { 
                trackingId = remoteMessage.getData().get("trackingId"); 
            } 
        } 
        if (message != null || title != null) { 
            sendNotification(message, title, imageUrl, deepLink, name, trackingId); 
        } else { 
            Log.d(TAG, "Empty Notification Received"); 
        } 
    } 

ส่วนที่2: สร้างการแจ้งเตือน

หากต้องการสร้างเหตุการณ์ตามการแจ้งเตือน ให้เปิดเนื้อหาการแจ้งเตือนและ ID รหัสติดตามในข้อมูล

private void sendNotification(String message, String title, String deeplink, String name, String trackingId) { 
    NotificationManager notificationManager = (NotificationManager) 
        this.getSystemService(Context.NOTIFICATION_SERVICE); 
 
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder( 
        this, 
        NOTIFICATION_CHANNEL_ID) 
        .setContentText(message) 
        .setContentTitle(title)              .setLargeIcon(getBitmapFromURL((imageUrl))) 
        .setPriority(NotificationCompat.PRIORITY_HIGH) 
        .setSmallIcon(android.R.drawable.ic_popup_reminder) 
        .setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL) 
        .setContentIntent(createContentIntent(this, deeplink, name, trackingId)) 
        .setDeleteIntent(createOnDismissedIntent(this, trackingId)) 
        .setStyle(new NotificationCompat.BigTextStyle() 
            .bigText(message)); 
 
    notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build()); 
} 
 
private PendingIntent createOnDismissedIntent(Context context, String trackingId) { 
    Intent intent = new Intent(context, NotificationDismissalReceiver.class); 
    intent.putExtra("TrackingId", trackingId); 
 
    return PendingIntent.getBroadcast(context.getApplicationContext(),0, intent, 0); 
} 
 
private PendingIntent createContentIntent(Context context, String deeplink, String name, String trackingId) { 
    Intent intent; 
 
    if (deeplink != null) { 
        intent = new Intent(Intent.ACTION_VIEW, Uri.parse(deeplink)); 
    } else { 
        intent = new Intent(this, MainActivity.class); 
    } 
    Bundle pushData = new Bundle(); 
    pushData.putString("name", name); 
 
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    intent.putExtras(pushData); 
    intent.putExtra("Source", "Notification"); 
    intent.putExtra("TrackingId", trackingId); 
 
    return PendingIntent.getActivity(this, NOTIFICATION_ID, intent, PendingIntent.FLAG_ONE_SHOT); 
} 
 
public static Bitmap getBitmapFromURL(String src) { 
    try { 
        URL url = new URL(src); 
        HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
        connection.setDoInput(true); 
        connection.connect(); 
        InputStream input = connection.getInputStream(); 
        Bitmap myBitmap = BitmapFactory.decodeStream(input); 
        return myBitmap; 
    } catch (IOException e) { 
        // Log exception 
        return null; 
    } 
} 

ส่วนที่ 3: สร้างเหตุการณ์ที่เปิดการแจ้งเตือน

จัดการแอปพลิเคชันที่เปิดผ่านการแจ้งเตือนใน MainActivity เพื่อรับ ID การติดตาม

@Override
        protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main); 
        String source = getIntent().getStringExtra("Source"); 
        if (source != null && !source.isEmpty()) 
        { 
            String trackingId = getIntent().getStringExtra("TrackingId"); 
            EventTrackerClient.sendEventToServer(this.getApplicationContext(), trackingId, EventType.Opened); 
        } 
        checkPlayServices(); 
        FirebaseService.createChannelAndHandleNotifications(getApplicationContext());