Panagiotis Triantafyllou

deh part7

......@@ -78,22 +78,22 @@
android:exported="false" />
<!-- FCM Service for push notifications -->
<service
android:name="ly.warp.sdk.services.FCMBaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<!-- <service-->
<!-- android:name="ly.warp.sdk.services.FCMBaseMessagingService"-->
<!-- android:exported="false">-->
<!-- <intent-filter>-->
<!-- <action android:name="com.google.firebase.MESSAGING_EVENT" />-->
<!-- </intent-filter>-->
<!-- </service>-->
<!-- Service used for handling Huawei Push Notifications, comment if we are in Google build -->
<service
android:name="ly.warp.sdk.services.HMSBaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.huawei.push.action.MESSAGING_EVENT" />
</intent-filter>
</service>
<!-- <service-->
<!-- android:name="ly.warp.sdk.services.HMSBaseMessagingService"-->
<!-- android:exported="false">-->
<!-- <intent-filter>-->
<!-- <action android:name="com.huawei.push.action.MESSAGING_EVENT" />-->
<!-- </intent-filter>-->
<!-- </service>-->
<receiver
android:name="ly.warp.sdk.receivers.ConnectivityChangedReceiver"
......
package ly.warp.sdk.utils.managers;
import static ly.warp.sdk.utils.constants.WarpConstants.CHANNEL_ID;
import static ly.warp.sdk.utils.constants.WarpConstants.RANDOM_MAX;
import static ly.warp.sdk.utils.constants.WarpConstants.RANDOM_MIN;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.RemoteViews;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import androidx.work.Constraints;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import com.google.firebase.messaging.RemoteMessage;
import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import ly.warp.sdk.Warply;
import ly.warp.sdk.activities.WarpViewActivity;
import ly.warp.sdk.io.models.PushCampaign;
import ly.warp.sdk.services.PushEventsWorkerService;
import ly.warp.sdk.utils.WarpUtils;
import ly.warp.sdk.utils.WarplyProperty;
/**
* Delegate class for handling Firebase Cloud Messaging (FCM) push notifications.
* This class allows client apps with existing FCM implementations to integrate Warply push handling.
*
* Usage:
* 1. Create an instance in your FirebaseMessagingService
* 2. Call handleMessage() from onMessageReceived()
* 3. Call handleNewToken() from onNewToken()
*/
public class WarplyFCMPushDelegate {
// ===========================================================
// Constants
// ===========================================================
private static final String KEY_TITLE = "alert";
private static final String KEY_SUBTITLE = "subtitle";
private static final String KEY_TICKER = "alert";
private static final String KEY_MESSAGE = "message";
private static final String KEY_PAYLOAD = "payload";
// ===========================================================
// Fields
// ===========================================================
private final Context context;
// ===========================================================
// Constructors
// ===========================================================
/**
* Creates a new WarplyFCMPushDelegate
* @param context Application context
*/
public WarplyFCMPushDelegate(@NonNull Context context) {
this.context = context;
}
// ===========================================================
// Public Methods
// ===========================================================
/**
* Call this method from your FirebaseMessagingService.onMessageReceived()
* @param remoteMessage The FCM message
* @return true if message was handled by Warply, false if it should be processed by your app
*/
public boolean handleMessage(@NonNull RemoteMessage remoteMessage) {
Bundle data = remoteMessage.toIntent().getExtras();
// Check if this message is for Warply
if (data == null || !data.containsKey("loyalty-action")) {
return false; // Not a Warply message, let the client handle it
}
// This is a Warply message, process it
PushCampaign pc = new PushCampaign(data);
// Set up analytics tracking
setUpPushEvents(pc);
WarpUtils.log("Warply received push with action: " + pc.getAction());
if (pc.getAction() == 0 && !pc.hasActions()) {
showCampaignNotification(context, pc);
} else {
showDefaultNotification(context, data);
}
return true; // Message was handled by Warply
}
/**
* Call this method from your FirebaseMessagingService.onNewToken()
* @param token The new FCM token
*/
public void handleNewToken(@NonNull String token) {
WarpUtils.setDeviceToken(context, token);
}
// ===========================================================
// Private Methods
// ===========================================================
private void setUpPushEvents(PushCampaign pc) {
Warply.getInitializer(context).init();
WarplyAnalyticsManager.logUserReceivedPush(pc);
Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build();
OneTimeWorkRequest sendEvent = new OneTimeWorkRequest.Builder(PushEventsWorkerService.class)
.setConstraints(constraints)
.setInitialDelay(defineRandomStart(), TimeUnit.MINUTES)
.build();
WorkManager.getInstance(context).enqueue(sendEvent);
}
private int defineRandomStart() {
if (Build.VERSION.SDK_INT >= 21) {
return ThreadLocalRandom.current().nextInt(RANDOM_MIN, RANDOM_MAX + 1);
} else {
SecureRandom rand = new SecureRandom();
return rand.nextInt((RANDOM_MAX - RANDOM_MIN) + 1) + RANDOM_MIN;
}
}
// ===========================================================
// Notification Methods
// ===========================================================
/**
* Shows a campaign notification
*/
private void showCampaignNotification(Context context, PushCampaign pc) {
showCampaignNotification(context, pc, null);
}
/**
* Shows a campaign notification with actions
*/
private void showCampaignNotification(Context context, PushCampaign pc, List<NotificationCompat.Action> actions) {
showCampaignNotification(context, pc, null, null);
}
/**
* Shows a campaign notification with actions and custom view
*/
private void showCampaignNotification(Context context, PushCampaign pc, List<NotificationCompat.Action> actions, RemoteViews remoteViews) {
WarpUtils.log("Showing campaign with session UUID: " + pc.getSessionUUID());
SecureRandom randomGenerator = new SecureRandom();
int uid = randomGenerator.nextInt(1000);
if (!TextUtils.isEmpty(pc.getSessionUUID())) {
uid = 0;
}
Intent newIntent = WarpViewActivity.createIntentFromSessionUUID(
context, pc.getSessionUUID(), "from_notification_status");
newIntent.setAction(Long.toString(System.currentTimeMillis()));
NotificationCompat.Builder b = new NotificationCompat.Builder(context, CHANNEL_ID);
if (pc.getNotificationStyle().equalsIgnoreCase(PushCampaign.NOTIFICATION_STYLE_BIG_PICTURE)
&& !TextUtils.isEmpty(pc.getBigPictureUrl())) {
//get big picture style
NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
bigPictureStyle.bigPicture(loadDrawable(pc.getBigPictureUrl()));
if (!TextUtils.isEmpty(pc.getSubtitle())) {
bigPictureStyle.setSummaryText(pc.getSubtitle());
}
b.setStyle(bigPictureStyle);
} else if (pc.getNotificationStyle().equalsIgnoreCase(PushCampaign.NOTIFICATION_STYLE_BIG_TEXT)
&& !TextUtils.isEmpty(pc.getBigText())) {
//get big picture style
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.bigText(pc.getBigText());
if (!TextUtils.isEmpty(pc.getSummaryText())) {
bigTextStyle.setSummaryText(pc.getSummaryText());
}
b.setStyle(bigTextStyle);
} else if (pc.getNotificationStyle().equalsIgnoreCase(PushCampaign.NOTIFICATION_STYLE_INBOX_STYLE)) {
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
for (int i = 0; i < pc.getInboxLines().size(); i++) {
inboxStyle.addLine(pc.getInboxLines().get(i));
}
if (!TextUtils.isEmpty(pc.getSummaryText())) {
inboxStyle.setSummaryText(pc.getSummaryText());
}
b.setStyle(inboxStyle);
}
b.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS);
b.setTicker(pc.getTicker());
b.setChannelId(CHANNEL_ID);
b.setContentTitle(pc.getTitle());
b.setContentText(pc.getSubtitle());
b.setSubText(pc.getContent());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
b.setContentIntent(PendingIntent.getActivity(context, uid, newIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_MUTABLE));
} else {
b.setContentIntent(PendingIntent.getActivity(context, uid, newIntent, PendingIntent.FLAG_ONE_SHOT));
}
b.setAutoCancel(true);
b.setOngoing(true);
b.setAutoCancel(true);
b.setSmallIcon(WarplyProperty.getPushIconResId(context));
b.setLargeIcon(loadDrawable(pc.getImageUrl()));
//Add remote view as content if exists
if (remoteViews != null) {
b.setContent(remoteViews);
}
if (pc.getSoundUri(context) == null)
b.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
else
b.setSound(pc.getSoundUri(context));
//If push has color
int color = WarplyProperty.getPushColor(context);
if (!TextUtils.isEmpty(pc.getColor())) {
try {
color = Color.parseColor(pc.getColor());
} catch (IllegalArgumentException iae) {
iae.printStackTrace();
}
}
b.setColor(color);
//add actions
if (actions != null) {
if (actions.size() > 0) {
for (NotificationCompat.Action action : actions) {
b.addAction(action);
}
}
}
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && nm != null) {
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, "notification_channel", NotificationManager.IMPORTANCE_DEFAULT);
nm.createNotificationChannel(notificationChannel);
Notification notification_build_with_largeicon = b.setChannelId(CHANNEL_ID).build();
notification_build_with_largeicon.flags = Notification.FLAG_AUTO_CANCEL; //notification with only large icon due to the two build notificaition is not canceled from bar
nm.notify(pc.getSessionUUID(), uid, notification_build_with_largeicon);
} else {
Notification notification_build_with_largeicon = b.build();
notification_build_with_largeicon.flags = Notification.FLAG_AUTO_CANCEL; //notification with only large icon due to the two build notificaition is not canceled from bar
if (nm != null) {
nm.notify(pc.getSessionUUID(), uid, notification_build_with_largeicon);
}
}
}
/**
* Shows a default notification for the app
*/
private void showDefaultNotification(Context context, Bundle data) {
String title = getNotificationTitle(data);
String ticker = getNotificationTicker(data);
String message = getNotificationMessage(data);
PushCampaign pc = new PushCampaign(data);
if (pc != null) {
PackageManager pm = context.getPackageManager();
Intent newIntent = pm.getLaunchIntentForPackage(context.getPackageName());
showNotification(context, pc, newIntent, null, null, null, 0);
}
}
/**
* Shows a notification with custom parameters
*/
private void showNotification(Context context, PushCampaign pc, Intent newIntent, List<NotificationCompat.Action> actions, RemoteViews remoteViews, String tag, int id) {
SecureRandom randomGenerator = new SecureRandom();
int uid = randomGenerator.nextInt(1000);
if (id > 0) {
uid = id;
}
WarpUtils.log("Showing notification with tag: " + tag + " and id: " + id);
NotificationCompat.Builder b = new NotificationCompat.Builder(context, CHANNEL_ID);
if (pc.getNotificationStyle().equalsIgnoreCase(PushCampaign.NOTIFICATION_STYLE_BIG_PICTURE)
&& !TextUtils.isEmpty(pc.getBigPictureUrl())) {
//get big picture style
NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
bigPictureStyle.bigPicture(loadDrawable(pc.getBigPictureUrl()));
if (!TextUtils.isEmpty(pc.getSubtitle())) {
bigPictureStyle.setSummaryText(pc.getSubtitle());
}
b.setStyle(bigPictureStyle);
} else if (pc.getNotificationStyle().equalsIgnoreCase(PushCampaign.NOTIFICATION_STYLE_BIG_TEXT)
&& !TextUtils.isEmpty(pc.getBigText())) {
//get big picture style
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.bigText(pc.getBigText());
if (!TextUtils.isEmpty(pc.getSummaryText())) {
bigTextStyle.setSummaryText(pc.getSummaryText());
}
b.setStyle(bigTextStyle);
} else if (pc.getNotificationStyle().equalsIgnoreCase(PushCampaign.NOTIFICATION_STYLE_INBOX_STYLE)) {
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
for (int i = 0; i < pc.getInboxLines().size(); i++) {
inboxStyle.addLine(pc.getInboxLines().get(i));
}
if (!TextUtils.isEmpty(pc.getSummaryText())) {
inboxStyle.setSummaryText(pc.getSummaryText());
}
b.setStyle(inboxStyle);
}
b.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS);
b.setTicker(pc.getTicker());
b.setChannelId(CHANNEL_ID);
b.setContentTitle(pc.getTitle());
b.setContentText(pc.getSubtitle());
b.setSubText(pc.getContent());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
b.setContentIntent(PendingIntent.getActivity(context, uid, newIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_MUTABLE));
} else {
b.setContentIntent(PendingIntent.getActivity(context, uid, newIntent, PendingIntent.FLAG_ONE_SHOT));
}
b.setAutoCancel(true);
b.setOngoing(true);
b.setAutoCancel(true);
b.setSmallIcon(WarplyProperty.getPushIconResId(context));
b.setLargeIcon(loadDrawable(pc.getImageUrl()));
if (remoteViews != null) {
b.setContent(remoteViews);
}
if (pc.getSoundUri(context) == null)
b.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
else
b.setSound(pc.getSoundUri(context));
//If push has color
int color = WarplyProperty.getPushColor(context);
if (!TextUtils.isEmpty(pc.getColor())) {
try {
color = Color.parseColor(pc.getColor());
} catch (IllegalArgumentException iae) {
iae.printStackTrace();
}
}
b.setColor(color);
//add actions
if (actions != null) {
if (actions.size() > 0) {
for (NotificationCompat.Action action : actions) {
b.addAction(action);
}
}
}
newIntent.setAction(Long.toString(System.currentTimeMillis()));
PendingIntent pi;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
pi = PendingIntent.getActivity(context, uid, newIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_MUTABLE);
} else {
pi = PendingIntent.getActivity(context, uid, newIntent, PendingIntent.FLAG_ONE_SHOT);
}
b.setContentIntent(pi);
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && nm != null) {
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, "notification_channel", NotificationManager.IMPORTANCE_DEFAULT);
nm.createNotificationChannel(notificationChannel);
Notification notification_build = b.setChannelId(CHANNEL_ID).build();
notification_build.flags = Notification.FLAG_AUTO_CANCEL;
nm.notify(pc.getSessionUUID(), uid, notification_build);
} else {
Notification notification_build = b.build();
notification_build.flags = Notification.FLAG_AUTO_CANCEL;
if (nm != null) {
nm.notify(pc.getSessionUUID(), uid, notification_build);
}
}
}
// ===========================================================
// Helper Methods
// ===========================================================
public JSONObject getPayload(Bundle data) {
String payloadStr = data.getString(KEY_PAYLOAD);
try {
JSONObject payload = new JSONObject(payloadStr);
return payload;
} catch (JSONException e) {
WarpUtils.log("Error with payload", e);
return null;
}
}
public String getNotificationTitle(Bundle data) {
return data.getString(KEY_TITLE);
}
public String getNotificationMessage(Bundle data) {
return data.getString(KEY_MESSAGE);
}
public String getNotificationTicker(Bundle data) {
return data.getString(KEY_TICKER);
}
public String getNotificationSubtitle(Bundle data) {
return data.getString(KEY_SUBTITLE);
}
private static Bitmap loadDrawable(String urlString) {
if (urlString == null || TextUtils.isEmpty(urlString))
return null;
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
if (!(urlConnection.getResponseCode() == HttpStatus.SC_OK))
return null;
InputStream is = urlConnection.getInputStream();
if (is == null) {
urlConnection.disconnect();
return null;
}
Bitmap b = BitmapFactory.decodeStream(is);
is.close();
urlConnection.disconnect();
return b;
} catch (IOException e) {
return null;
}
}
}
package ly.warp.sdk.utils.managers;
import static ly.warp.sdk.utils.constants.WarpConstants.CHANNEL_ID;
import static ly.warp.sdk.utils.constants.WarpConstants.RANDOM_MAX;
import static ly.warp.sdk.utils.constants.WarpConstants.RANDOM_MIN;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.RemoteViews;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import androidx.work.Constraints;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import com.huawei.hms.push.RemoteMessage;
import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import ly.warp.sdk.Warply;
import ly.warp.sdk.activities.WarpViewActivity;
import ly.warp.sdk.io.models.PushCampaign;
import ly.warp.sdk.services.PushEventsWorkerService;
import ly.warp.sdk.utils.WarpUtils;
import ly.warp.sdk.utils.WarplyProperty;
/**
* Delegate class for handling Huawei Mobile Services (HMS) push notifications.
* This class allows client apps with existing HMS implementations to integrate Warply push handling.
*
* Usage:
* 1. Create an instance in your HmsMessageService
* 2. Call handleMessage() from onMessageReceived()
* 3. Call handleNewToken() from onNewToken()
*/
public class WarplyHMSPushDelegate {
// ===========================================================
// Constants
// ===========================================================
private static final String KEY_TITLE = "alert";
private static final String KEY_SUBTITLE = "subtitle";
private static final String KEY_TICKER = "alert";
private static final String KEY_MESSAGE = "message";
private static final String KEY_PAYLOAD = "payload";
// ===========================================================
// Fields
// ===========================================================
private final Context context;
private static Bitmap bFinal = null;
// ===========================================================
// URLThread class
// ===========================================================
public static class URLThread extends Thread {
private String urlString = "";
public URLThread(String url) {
this.urlString = url;
}
@Override
public void run() {
try {
URL url;
HttpURLConnection urlConnection = null;
url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
if (!(urlConnection.getResponseCode() == HttpStatus.SC_OK)) {
bFinal = null;
return;
}
InputStream is = urlConnection.getInputStream();
if (is == null) {
urlConnection.disconnect();
bFinal = null;
return;
}
Bitmap b = BitmapFactory.decodeStream(is);
is.close();
urlConnection.disconnect();
bFinal = b;
} catch (Exception ex) {
bFinal = null;
ex.printStackTrace();
}
}
}
// ===========================================================
// Constructors
// ===========================================================
/**
* Creates a new WarplyHMSPushDelegate
* @param context Application context
*/
public WarplyHMSPushDelegate(@NonNull Context context) {
this.context = context;
}
// ===========================================================
// Public Methods
// ===========================================================
/**
* Call this method from your HmsMessageService.onMessageReceived()
* @param remoteMessage The HMS message
* @return true if message was handled by Warply, false if it should be processed by your app
*/
public boolean handleMessage(@NonNull RemoteMessage remoteMessage) {
JSONObject data = new JSONObject(remoteMessage.getDataOfMap());
// Check if this message is for Warply
if (data == null || !data.has("loyalty-action")) {
return false; // Not a Warply message, let the client handle it
}
// This is a Warply message, process it
PushCampaign pc = new PushCampaign(data);
// Set up analytics tracking
setUpPushEvents(pc);
WarpUtils.log("Warply received push with action: " + pc.getAction());
if (pc.getAction() == 0 && !pc.hasActions()) {
showCampaignNotification(context, pc);
} else {
Bundle bundledData = null;
try {
bundledData = jsonToBundle(data);
} catch (JSONException e) {
e.printStackTrace();
}
showDefaultNotification(context, bundledData);
}
return true; // Message was handled by Warply
}
/**
* Call this method from your HmsMessageService.onNewToken()
* @param token The new HMS token
*/
public void handleNewToken(@NonNull String token) {
WarpUtils.setDeviceToken(context, token);
}
// ===========================================================
// Private Methods
// ===========================================================
private void setUpPushEvents(PushCampaign pc) {
Warply.getInitializer(context).init();
WarplyAnalyticsManager.logUserReceivedPush(pc);
Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build();
OneTimeWorkRequest sendEvent = new OneTimeWorkRequest.Builder(PushEventsWorkerService.class)
.setConstraints(constraints)
.setInitialDelay(defineRandomStart(), TimeUnit.MINUTES)
.build();
WorkManager.getInstance(context).enqueue(sendEvent);
}
private int defineRandomStart() {
if (Build.VERSION.SDK_INT >= 21) {
return ThreadLocalRandom.current().nextInt(RANDOM_MIN, RANDOM_MAX + 1);
} else {
SecureRandom rand = new SecureRandom();
return rand.nextInt((RANDOM_MAX - RANDOM_MIN) + 1) + RANDOM_MIN;
}
}
// ===========================================================
// Notification Methods
// ===========================================================
/**
* Shows a campaign notification
*/
private void showCampaignNotification(Context context, PushCampaign pc) {
showCampaignNotification(context, pc, null);
}
/**
* Shows a campaign notification with actions
*/
private void showCampaignNotification(Context context, PushCampaign pc, List<NotificationCompat.Action> actions) {
showCampaignNotification(context, pc, null, null);
}
/**
* Shows a campaign notification with actions and custom view
*/
private void showCampaignNotification(Context context, PushCampaign pc, List<NotificationCompat.Action> actions, RemoteViews remoteViews) {
WarpUtils.log("Showing campaign with session UUID: " + pc.getSessionUUID());
SecureRandom randomGenerator = new SecureRandom();
int uid = randomGenerator.nextInt(1000);
if (!TextUtils.isEmpty(pc.getSessionUUID())) {
uid = 0;
}
Intent newIntent = WarpViewActivity.createIntentFromSessionUUID(
context, pc.getSessionUUID(), "from_notification_status");
newIntent.setAction(Long.toString(System.currentTimeMillis()));
NotificationCompat.Builder b = new NotificationCompat.Builder(context, CHANNEL_ID);
if (pc.getNotificationStyle().equalsIgnoreCase(PushCampaign.NOTIFICATION_STYLE_BIG_PICTURE)
&& !TextUtils.isEmpty(pc.getBigPictureUrl())) {
//get big picture style
NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
bigPictureStyle.bigPicture(loadDrawable(pc.getBigPictureUrl()));
if (!TextUtils.isEmpty(pc.getSubtitle())) {
bigPictureStyle.setSummaryText(pc.getSubtitle());
}
b.setStyle(bigPictureStyle);
} else if (pc.getNotificationStyle().equalsIgnoreCase(PushCampaign.NOTIFICATION_STYLE_BIG_TEXT)
&& !TextUtils.isEmpty(pc.getBigText())) {
//get big picture style
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.bigText(pc.getBigText());
if (!TextUtils.isEmpty(pc.getSummaryText())) {
bigTextStyle.setSummaryText(pc.getSummaryText());
}
b.setStyle(bigTextStyle);
} else if (pc.getNotificationStyle().equalsIgnoreCase(PushCampaign.NOTIFICATION_STYLE_INBOX_STYLE)) {
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
for (int i = 0; i < pc.getInboxLines().size(); i++) {
inboxStyle.addLine(pc.getInboxLines().get(i));
}
if (!TextUtils.isEmpty(pc.getSummaryText())) {
inboxStyle.setSummaryText(pc.getSummaryText());
}
b.setStyle(inboxStyle);
}
b.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS);
b.setTicker(pc.getTicker());
b.setChannelId(CHANNEL_ID);
b.setContentTitle(pc.getTitle());
b.setContentText(pc.getSubtitle());
b.setSubText(pc.getContent());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
b.setContentIntent(PendingIntent.getActivity(context, uid, newIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_MUTABLE));
} else {
b.setContentIntent(PendingIntent.getActivity(context, uid, newIntent, PendingIntent.FLAG_ONE_SHOT));
}
b.setAutoCancel(true);
b.setOngoing(true);
b.setAutoCancel(true);
b.setSmallIcon(WarplyProperty.getPushIconResId(context));
b.setLargeIcon(loadDrawable(pc.getImageUrl()));
//Add remote view as content if exists
if (remoteViews != null) {
b.setContent(remoteViews);
}
if (pc.getSoundUri(context) == null)
b.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
else
b.setSound(pc.getSoundUri(context));
//If push has color
int color = WarplyProperty.getPushColor(context);
if (!TextUtils.isEmpty(pc.getColor())) {
try {
color = Color.parseColor(pc.getColor());
} catch (IllegalArgumentException iae) {
iae.printStackTrace();
}
}
b.setColor(color);
//add actions
if (actions != null) {
if (actions.size() > 0) {
for (NotificationCompat.Action action : actions) {
b.addAction(action);
}
}
}
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && nm != null) {
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, "notification_channel", NotificationManager.IMPORTANCE_DEFAULT);
nm.createNotificationChannel(notificationChannel);
Notification notification_build_with_largeicon = b.setChannelId(CHANNEL_ID).build();
notification_build_with_largeicon.flags = Notification.FLAG_AUTO_CANCEL; //notification with only large icon due to the two build notificaition is not canceled from bar
nm.notify(pc.getSessionUUID(), uid, notification_build_with_largeicon);
} else {
Notification notification_build_with_largeicon = b.build();
notification_build_with_largeicon.flags = Notification.FLAG_AUTO_CANCEL; //notification with only large icon due to the two build notificaition is not canceled from bar
if (nm != null) {
nm.notify(pc.getSessionUUID(), uid, notification_build_with_largeicon);
}
}
}
/**
* Shows a default notification for the app
*/
private void showDefaultNotification(Context context, Bundle data) {
String title = getNotificationTitle(data);
String ticker = getNotificationTicker(data);
String message = getNotificationMessage(data);
PushCampaign pc = new PushCampaign(data);
if (pc != null) {
PackageManager pm = context.getPackageManager();
Intent newIntent = pm.getLaunchIntentForPackage(context.getPackageName());
showNotification(context, pc, newIntent, null, null, null, 0);
}
}
/**
* Shows a notification with custom parameters
*/
private void showNotification(Context context, PushCampaign pc, Intent newIntent, List<NotificationCompat.Action> actions, RemoteViews remoteViews, String tag, int id) {
SecureRandom randomGenerator = new SecureRandom();
int uid = randomGenerator.nextInt(1000);
if (id > 0) {
uid = id;
}
WarpUtils.log("Showing notification with tag: " + tag + " and id: " + id);
NotificationCompat.Builder b = new NotificationCompat.Builder(context, CHANNEL_ID);
if (pc.getNotificationStyle().equalsIgnoreCase(PushCampaign.NOTIFICATION_STYLE_BIG_PICTURE)
&& !TextUtils.isEmpty(pc.getBigPictureUrl())) {
//get big picture style
NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
bigPictureStyle.bigPicture(loadDrawable(pc.getBigPictureUrl()));
if (!TextUtils.isEmpty(pc.getSubtitle())) {
bigPictureStyle.setSummaryText(pc.getSubtitle());
}
b.setStyle(bigPictureStyle);
} else if (pc.getNotificationStyle().equalsIgnoreCase(PushCampaign.NOTIFICATION_STYLE_BIG_TEXT)
&& !TextUtils.isEmpty(pc.getBigText())) {
//get big picture style
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.bigText(pc.getBigText());
if (!TextUtils.isEmpty(pc.getSummaryText())) {
bigTextStyle.setSummaryText(pc.getSummaryText());
}
b.setStyle(bigTextStyle);
} else if (pc.getNotificationStyle().equalsIgnoreCase(PushCampaign.NOTIFICATION_STYLE_INBOX_STYLE)) {
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
for (int i = 0; i < pc.getInboxLines().size(); i++) {
inboxStyle.addLine(pc.getInboxLines().get(i));
}
if (!TextUtils.isEmpty(pc.getSummaryText())) {
inboxStyle.setSummaryText(pc.getSummaryText());
}
b.setStyle(inboxStyle);
}
b.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS);
b.setTicker(pc.getTicker());
b.setChannelId(CHANNEL_ID);
b.setContentTitle(pc.getTitle());
b.setContentText(pc.getSubtitle());
b.setSubText(pc.getContent());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
b.setContentIntent(PendingIntent.getActivity(context, uid, newIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_MUTABLE));
} else {
b.setContentIntent(PendingIntent.getActivity(context, uid, newIntent, PendingIntent.FLAG_ONE_SHOT));
}
b.setAutoCancel(true);
b.setOngoing(true);
b.setAutoCancel(true);
b.setSmallIcon(WarplyProperty.getPushIconResId(context));
b.setLargeIcon(loadDrawable(pc.getImageUrl()));
if (remoteViews != null) {
b.setContent(remoteViews);
}
if (pc.getSoundUri(context) == null)
b.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
else
b.setSound(pc.getSoundUri(context));
//If push has color
int color = WarplyProperty.getPushColor(context);
if (!TextUtils.isEmpty(pc.getColor())) {
try {
color = Color.parseColor(pc.getColor());
} catch (IllegalArgumentException iae) {
iae.printStackTrace();
}
}
b.setColor(color);
//add actions
if (actions != null) {
if (actions.size() > 0) {
for (NotificationCompat.Action action : actions) {
b.addAction(action);
}
}
}
newIntent.setAction(Long.toString(System.currentTimeMillis()));
PendingIntent pi;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
pi = PendingIntent.getActivity(context, uid, newIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_MUTABLE);
} else {
pi = PendingIntent.getActivity(context, uid, newIntent, PendingIntent.FLAG_ONE_SHOT);
}
b.setContentIntent(pi);
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && nm != null) {
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, "notification_channel", NotificationManager.IMPORTANCE_DEFAULT);
nm.createNotificationChannel(notificationChannel);
Notification notification_build = b.setChannelId(CHANNEL_ID).build();
notification_build.flags = Notification.FLAG_AUTO_CANCEL;
nm.notify(pc.getSessionUUID(), uid, notification_build);
} else {
Notification notification_build = b.build();
notification_build.flags = Notification.FLAG_AUTO_CANCEL;
if (nm != null) {
nm.notify(pc.getSessionUUID(), uid, notification_build);
}
}
}
// ===========================================================
// Helper Methods
// ===========================================================
public JSONObject getPayload(Bundle data) {
String payloadStr = data.getString(KEY_PAYLOAD);
try {
JSONObject payload = new JSONObject(payloadStr);
return payload;
} catch (JSONException e) {
WarpUtils.log("Error with payload", e);
return null;
}
}
public String getNotificationTitle(Bundle data) {
return data.getString(KEY_TITLE);
}
public String getNotificationMessage(Bundle data) {
return data.getString(KEY_MESSAGE);
}
public String getNotificationTicker(Bundle data) {
return data.getString(KEY_TICKER);
}
public String getNotificationSubtitle(Bundle data) {
return data.getString(KEY_SUBTITLE);
}
private static Bitmap loadDrawable(final String urlString) {
if (urlString == null || TextUtils.isEmpty(urlString))
return null;
URLThread urlThread = new URLThread(urlString);
try {
urlThread.start();
urlThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return bFinal;
}
/**
* Convert a JSONObject to a Bundle
*/
public static Bundle jsonToBundle(JSONObject jsonObject) throws JSONException {
Bundle bundle = new Bundle();
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
String value = jsonObject.getString(key);
bundle.putString(key, value);
}
return bundle;
}
}