-
-
Notifications
You must be signed in to change notification settings - Fork 32
/
TiFirebaseMessagingService.java
360 lines (313 loc) · 14.3 KB
/
TiFirebaseMessagingService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
package firebase.cloudmessaging;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import androidx.preference.PreferenceManager;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.util.TiConvert;
import org.appcelerator.titanium.util.TiRHelper;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import me.leolin.shortcutbadger.ShortcutBadger;
public class TiFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FirebaseMsgService";
private static final AtomicInteger atomic = new AtomicInteger(0);
@Override
public void onNewToken(String s) {
super.onNewToken(s);
CloudMessagingModule module = CloudMessagingModule.getInstance();
if (module != null) {
module.onTokenRefresh(s);
}
Log.d(TAG, "New token: " + s);
}
@Override
public void onMessageSent(String msgID) {
Log.d(TAG, "Message sent: " + msgID);
}
@Override
public void onSendError(String msgID, Exception exception) {
Log.e(TAG, "Send Error: " + msgID + " " + exception);
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
HashMap<String, Object> msg = new HashMap<String, Object>();
CloudMessagingModule module = CloudMessagingModule.getInstance();
Boolean appInForeground = TiApplication.isCurrentActivityInForeground();
Boolean isVisible = true;
if (remoteMessage.getData().size() > 0) {
// data message
isVisible = showNotification(remoteMessage);
}
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
msg.put("title", remoteMessage.getNotification().getTitle());
msg.put("body", remoteMessage.getNotification().getBody());
isVisible = true;
} else {
Log.d(TAG, "Data message: " + remoteMessage.getData());
}
msg.put("from", remoteMessage.getFrom());
msg.put("to", remoteMessage.getTo());
msg.put("ttl", remoteMessage.getTtl());
msg.put("messageId", remoteMessage.getMessageId());
msg.put("messageType", remoteMessage.getMessageType());
msg.put("data", new KrollDict(remoteMessage.getData()));
msg.put("sendTime", remoteMessage.getSentTime());
if (isVisible || appInForeground) {
// app is in foreground or notification was show - send data to event receiver
if (module != null) {
module.onMessageReceived(msg);
}
}
}
private Boolean showNotification(RemoteMessage remoteMessage) {
CloudMessagingModule module = CloudMessagingModule.getInstance();
Map<String, String> params = remoteMessage.getData();
JSONObject jsonData = new JSONObject(params);
Boolean appInForeground = TiApplication.isCurrentActivityInForeground();
Boolean showNotification = true;
Context context = getApplicationContext();
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
int builder_defaults = 0;
String parseTitle = "";
String parseText = "";
boolean isParse = false;
if (appInForeground) {
showNotification = false;
}
if (params.get("force_show_in_foreground") != null && params.get("force_show_in_foreground") != "") {
showNotification = showNotification || TiConvert.toBoolean(params.get("force_show_in_foreground"), false);
}
if (module != null && module.forceShowInForeground()) {
showNotification = module.forceShowInForeground();
}
if (TiConvert.toBoolean(params.get("vibrate"), false)) {
builder_defaults |= Notification.DEFAULT_VIBRATE;
}
if (params.get("title") == null && params.get("alert") == null && params.get("message") == null
&& params.get("big_text") == null && params.get("big_text_summary") == null && params.get("ticker") == null
&& params.get("image") == null) {
// no actual content - don't show it
showNotification = false;
}
// Check if it is a default Parse/Sashido message ("data.data.alert")
if (params.get("data") != null) {
try {
JSONObject localJsonData = new JSONObject(params.get("data"));
if (localJsonData.get("alert") != null) {
// Parse notification
showNotification = true;
isParse = true;
parseTitle = localJsonData.get("alert").toString();
if (localJsonData.get("text") != null) {
parseText = localJsonData.get("text").toString();
}
}
} catch (JSONException e) {
//
}
}
String priorityString = params.get("priority");
int priority = NotificationManager.IMPORTANCE_MAX;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && priorityString != null && !priorityString.isEmpty()) {
if (priorityString.equalsIgnoreCase("low")) {
priority = NotificationManager.IMPORTANCE_LOW;
} else if (priorityString.equalsIgnoreCase("min")) {
priority = NotificationManager.IMPORTANCE_MIN;
} else if (priorityString.equalsIgnoreCase("max")) {
priority = NotificationManager.IMPORTANCE_MAX;
} else if (priorityString.equalsIgnoreCase("default")) {
priority = NotificationManager.IMPORTANCE_DEFAULT;
} else if (priorityString.equalsIgnoreCase("high")) {
priority = NotificationManager.IMPORTANCE_HIGH;
} else {
priority = TiConvert.toInt(priorityString, 1);
}
}
if (params.get("sound") != null && params.get("sound") != "" && !params.get("sound").isEmpty()) {
defaultSoundUri = Utils.getSoundUri(params.get("sound"));
Log.d(TAG, "showNotification custom sound: " + defaultSoundUri);
} else {
builder_defaults |= Notification.DEFAULT_SOUND;
}
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("titanium.firebase.cloudmessaging.message", jsonData.toString());
editor.commit();
try {
// adding normal notification fields to the fcm_data node
if (!remoteMessage.getNotification().getTitle().isEmpty()) {
jsonData.put("notification_title", remoteMessage.getNotification().getTitle());
}
if (!remoteMessage.getNotification().getBody().isEmpty()) {
jsonData.put("notification_body", remoteMessage.getNotification().getBody());
}
} catch (Exception ex) {
Log.e(TAG, "Error adding fields: " + ex.getMessage());
}
if (!showNotification) {
// hidden notification - still send broadcast with data for next app start
Intent i = new Intent();
i.addCategory(Intent.CATEGORY_LAUNCHER);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("fcm_data", jsonData.toString());
sendBroadcast(i);
return false;
}
Intent notificationIntent = new Intent(this, PushHandlerActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
notificationIntent.putExtra("fcm_data", jsonData.toString());
int requestCode = (int) (System.currentTimeMillis() / 1000);
PendingIntent contentIntent =
PendingIntent.getActivity(this, requestCode, notificationIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_ONE_SHOT);
// Start building notification
NotificationCompat.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "default";
if (params.get("channelId") != null && params.get("channelId") != "") {
channelId = params.get("channelId");
}
builder = new NotificationCompat.Builder(context, channelId);
} else {
builder = new NotificationCompat.Builder(context);
}
builder.setContentIntent(contentIntent);
builder.setAutoCancel(true);
builder.setPriority(priority);
builder.setContentTitle(params.get("title"));
if (params.get("alert") != null) {
// OneSignal uses alert for the message
builder.setContentText(params.get("alert"));
} else {
builder.setContentText(params.get("message"));
}
if (isParse) {
builder.setContentTitle(parseTitle);
if (!parseText.equals("")) {
builder.setContentText(parseText);
}
}
builder.setTicker(params.get("ticker"));
builder.setDefaults(builder_defaults);
builder.setSound(defaultSoundUri);
// BigText
if (params.get("big_text") != null && params.get("big_text") != "") {
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.bigText(params.get("big_text"));
if (params.get("big_text_summary") != null && params.get("big_text_summary") != "") {
bigTextStyle.setSummaryText(params.get("big_text_summary"));
}
builder.setStyle(bigTextStyle);
}
// Icons
try {
int smallIcon = this.getResource("drawable", "notificationicon");
int smallAppIcon = this.getResource("drawable", "appicon");
if (smallIcon > 0) {
// use custom icon
builder.setSmallIcon(smallIcon);
} else if (smallAppIcon > 0) {
// use app icon
builder.setSmallIcon(smallAppIcon);
} else {
// fallback
builder.setSmallIcon(android.R.drawable.stat_sys_warning);
}
} catch (Exception ex) {
Log.e(TAG, "Smallicon exception: " + ex.getMessage());
}
if (params.get("color") != null && params.get("color") != "") {
try {
int color = TiConvert.toColor(params.get("color"), TiApplication.getAppCurrentActivity());
builder.setColor(color);
builder.setColorized(true);
} catch (Exception ex) {
Log.e(TAG, "Color exception: " + ex.getMessage());
}
}
// Large icon
if (params.get("icon") != null && params.get("icon") != "") {
try {
Bitmap icon = this.getBitmapFromURL(params.get("icon"));
//Check if the icon should be displayed as a circle
if (jsonData.optBoolean("rounded_large_icon")) {
//Converting the icon Bitmap to a circle shaped Bitmap
icon = Utils.getCircleBitmap(icon);
}
builder.setLargeIcon(icon);
} catch (Exception ex) {
Log.e(TAG, "Icon exception: " + ex.getMessage());
}
}
// Large icon
if (params.get("image") != null && params.get("image") != "") {
try {
Bitmap image = this.getBitmapFromURL(params.get("image"));
NotificationCompat.BigPictureStyle notiStyle = new NotificationCompat.BigPictureStyle();
notiStyle.bigPicture(image);
builder.setStyle(notiStyle);
} catch (Exception ex) {
Log.e(TAG, "Image exception: " + ex.getMessage());
}
}
// Badge number
if (params.get("badge") != null && params.get("badge") != "") {
ShortcutBadger.applyCount(context, TiConvert.toInt(params.get("badge"), 1));
builder.setNumber(TiConvert.toInt(params.get("badge"), 1));
}
int id = 0;
if (params != null && params.get("id") != "") {
// ensure that the id sent from the server is negative to prevent
// collision with the atomic integer
id = TiConvert.toInt(params.get("id"), 0);
}
if (id == 0) {
id = atomic.getAndIncrement();
}
// Send
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(id, builder.build());
return true;
}
private Bitmap getBitmapFromURL(String src) throws Exception {
HttpURLConnection connection = (HttpURLConnection) (new URL(src)).openConnection();
connection.setDoInput(true);
connection.setUseCaches(false); // Android BUG
connection.connect();
return BitmapFactory.decodeStream(new BufferedInputStream(connection.getInputStream()));
}
private int getResource(String type, String name) {
int icon = 0;
if (name != null) {
int index = name.lastIndexOf(".");
if (index > 0)
name = name.substring(0, index);
try {
icon = TiRHelper.getApplicationResource(type + "." + name);
} catch (TiRHelper.ResourceNotFoundException ex) {
Log.w(TAG, type + "." + name + " not found; make sure it's in platform/android/res/" + type);
}
}
return icon;
}
}