The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1650 lines
84KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. namespace juce
  20. {
  21. #if __ANDROID_API__ >= 21
  22. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  23. METHOD (build, "build", "()Landroid/media/AudioAttributes;") \
  24. METHOD (constructor, "<init>", "()V") \
  25. METHOD (setContentType, "setContentType", "(I)Landroid/media/AudioAttributes$Builder;") \
  26. METHOD (setUsage, "setUsage", "(I)Landroid/media/AudioAttributes$Builder;")
  27. DECLARE_JNI_CLASS (AudioAttributesBuilder, "android/media/AudioAttributes$Builder")
  28. #undef JNI_CLASS_MEMBERS
  29. #endif
  30. #if __ANDROID_API__ >= 26
  31. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  32. METHOD (constructor, "<init>", "(Ljava/lang/String;Ljava/lang/CharSequence;I)V") \
  33. METHOD (enableLights, "enableLights", "(Z)V") \
  34. METHOD (enableVibration, "enableVibration", "(Z)V") \
  35. METHOD (setBypassDnd, "setBypassDnd", "(Z)V") \
  36. METHOD (setDescription, "setDescription", "(Ljava/lang/String;)V") \
  37. METHOD (setGroup, "setGroup", "(Ljava/lang/String;)V") \
  38. METHOD (setImportance, "setImportance", "(I)V") \
  39. METHOD (setLightColor, "setLightColor", "(I)V") \
  40. METHOD (setLockscreenVisibility, "setLockscreenVisibility", "(I)V") \
  41. METHOD (setShowBadge, "setShowBadge", "(Z)V") \
  42. METHOD (setSound, "setSound", "(Landroid/net/Uri;Landroid/media/AudioAttributes;)V") \
  43. METHOD (setVibrationPattern, "setVibrationPattern", "([J)V")
  44. DECLARE_JNI_CLASS (NotificationChannel, "android/app/NotificationChannel");
  45. #undef JNI_CLASS_MEMBERS
  46. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  47. METHOD (constructor, "<init>", "(Ljava/lang/String;Ljava/lang/CharSequence;)V")
  48. DECLARE_JNI_CLASS (NotificationChannelGroup, "android/app/NotificationChannelGroup");
  49. #undef JNI_CLASS_MEMBERS
  50. #endif
  51. #if __ANDROID_API__ >= 19
  52. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  53. FIELD (extras, "extras", "Landroid/os/Bundle;")
  54. DECLARE_JNI_CLASS (AndroidNotification, "android/app/Notification");
  55. #undef JNI_CLASS_MEMBERS
  56. #endif
  57. #if __ANDROID_API__ >= 20
  58. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  59. METHOD (addExtras, "addExtras", "(Landroid/os/Bundle;)Landroid/app/Notification$Action$Builder;") \
  60. METHOD (addRemoteInput, "addRemoteInput", "(Landroid/app/RemoteInput;)Landroid/app/Notification$Action$Builder;") \
  61. METHOD (constructor, "<init>", "(ILjava/lang/CharSequence;Landroid/app/PendingIntent;)V") \
  62. METHOD (build, "build", "()Landroid/app/Notification$Action;")
  63. DECLARE_JNI_CLASS (NotificationActionBuilder, "android/app/Notification$Action$Builder");
  64. #undef JNI_CLASS_MEMBERS
  65. #endif
  66. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  67. METHOD (getNotification, "getNotification", "()Landroid/app/Notification;") \
  68. METHOD (setAutoCancel, "setAutoCancel", "(Z)Landroid/app/Notification$Builder;") \
  69. METHOD (setContentInfo, "setContentInfo", "(Ljava/lang/CharSequence;)Landroid/app/Notification$Builder;") \
  70. METHOD (setContentIntent, "setContentIntent", "(Landroid/app/PendingIntent;)Landroid/app/Notification$Builder;") \
  71. METHOD (setContentText, "setContentText", "(Ljava/lang/CharSequence;)Landroid/app/Notification$Builder;") \
  72. METHOD (setContentTitle, "setContentTitle", "(Ljava/lang/CharSequence;)Landroid/app/Notification$Builder;") \
  73. METHOD (setDefaults, "setDefaults", "(I)Landroid/app/Notification$Builder;") \
  74. METHOD (setDeleteIntent, "setDeleteIntent", "(Landroid/app/PendingIntent;)Landroid/app/Notification$Builder;") \
  75. METHOD (setLargeIcon, "setLargeIcon", "(Landroid/graphics/Bitmap;)Landroid/app/Notification$Builder;") \
  76. METHOD (setLights, "setLights", "(III)Landroid/app/Notification$Builder;") \
  77. METHOD (setNumber, "setNumber", "(I)Landroid/app/Notification$Builder;") \
  78. METHOD (setOngoing, "setOngoing", "(Z)Landroid/app/Notification$Builder;") \
  79. METHOD (setOnlyAlertOnce, "setOnlyAlertOnce", "(Z)Landroid/app/Notification$Builder;") \
  80. METHOD (setProgress, "setProgress", "(IIZ)Landroid/app/Notification$Builder;") \
  81. METHOD (setSmallIcon, "setSmallIcon", "(I)Landroid/app/Notification$Builder;") \
  82. METHOD (setSound, "setSound", "(Landroid/net/Uri;)Landroid/app/Notification$Builder;") \
  83. METHOD (setTicker, "setTicker", "(Ljava/lang/CharSequence;)Landroid/app/Notification$Builder;") \
  84. METHOD (setVibrate, "setVibrate", "([J)Landroid/app/Notification$Builder;") \
  85. METHOD (setWhen, "setWhen", "(J)Landroid/app/Notification$Builder;")
  86. DECLARE_JNI_CLASS (NotificationBuilderBase, "android/app/Notification$Builder");
  87. #undef JNI_CLASS_MEMBERS
  88. #if __ANDROID_API__ >= 16
  89. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  90. METHOD (addAction, "addAction", "(ILjava/lang/CharSequence;Landroid/app/PendingIntent;)Landroid/app/Notification$Builder;") \
  91. METHOD (build, "build", "()Landroid/app/Notification;") \
  92. METHOD (setPriority, "setPriority", "(I)Landroid/app/Notification$Builder;") \
  93. METHOD (setSubText, "setSubText", "(Ljava/lang/CharSequence;)Landroid/app/Notification$Builder;") \
  94. METHOD (setUsesChronometer, "setUsesChronometer", "(Z)Landroid/app/Notification$Builder;")
  95. DECLARE_JNI_CLASS (NotificationBuilderApi16, "android/app/Notification$Builder");
  96. #undef JNI_CLASS_MEMBERS
  97. #endif
  98. #if __ANDROID_API__ >= 17
  99. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  100. METHOD (setShowWhen, "setShowWhen", "(Z)Landroid/app/Notification$Builder;")
  101. DECLARE_JNI_CLASS (NotificationBuilderApi17, "android/app/Notification$Builder");
  102. #undef JNI_CLASS_MEMBERS
  103. #endif
  104. #if __ANDROID_API__ >= 20
  105. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  106. METHOD (addAction, "addAction", "(Landroid/app/Notification$Action;)Landroid/app/Notification$Builder;") \
  107. METHOD (addExtras, "addExtras", "(Landroid/os/Bundle;)Landroid/app/Notification$Builder;") \
  108. METHOD (setLocalOnly, "setLocalOnly", "(Z)Landroid/app/Notification$Builder;") \
  109. METHOD (setGroup, "setGroup", "(Ljava/lang/String;)Landroid/app/Notification$Builder;") \
  110. METHOD (setGroupSummary, "setGroupSummary", "(Z)Landroid/app/Notification$Builder;") \
  111. METHOD (setSortKey, "setSortKey", "(Ljava/lang/String;)Landroid/app/Notification$Builder;")
  112. DECLARE_JNI_CLASS (NotificationBuilderApi20, "android/app/Notification$Builder");
  113. #undef JNI_CLASS_MEMBERS
  114. #endif
  115. #if __ANDROID_API__ >= 21
  116. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  117. METHOD (addPerson, "addPerson", "(Ljava/lang/String;)Landroid/app/Notification$Builder;") \
  118. METHOD (setCategory, "setCategory", "(Ljava/lang/String;)Landroid/app/Notification$Builder;") \
  119. METHOD (setColor, "setColor", "(I)Landroid/app/Notification$Builder;") \
  120. METHOD (setPublicVersion, "setPublicVersion", "(Landroid/app/Notification;)Landroid/app/Notification$Builder;") \
  121. METHOD (setVisibility, "setVisibility", "(I)Landroid/app/Notification$Builder;")
  122. DECLARE_JNI_CLASS (NotificationBuilderApi21, "android/app/Notification$Builder");
  123. #undef JNI_CLASS_MEMBERS
  124. #endif
  125. #if __ANDROID_API__ >= 24
  126. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  127. METHOD (setChronometerCountDown, "setChronometerCountDown", "(Z)Landroid/app/Notification$Builder;")
  128. DECLARE_JNI_CLASS (NotificationBuilderApi24, "android/app/Notification$Builder");
  129. #undef JNI_CLASS_MEMBERS
  130. #endif
  131. #if __ANDROID_API__ >= 26
  132. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  133. METHOD (setBadgeIconType, "setBadgeIconType", "(I)Landroid/app/Notification$Builder;") \
  134. METHOD (setGroupAlertBehavior, "setGroupAlertBehavior", "(I)Landroid/app/Notification$Builder;") \
  135. METHOD (setTimeoutAfter, "setTimeoutAfter", "(J)Landroid/app/Notification$Builder;")
  136. DECLARE_JNI_CLASS (NotificationBuilderApi26, "android/app/Notification$Builder");
  137. #undef JNI_CLASS_MEMBERS
  138. #endif
  139. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  140. METHOD (cancel, "cancel", "(Ljava/lang/String;I)V") \
  141. METHOD (cancelAll, "cancelAll", "()V") \
  142. METHOD (notify, "notify", "(Ljava/lang/String;ILandroid/app/Notification;)V")
  143. DECLARE_JNI_CLASS (NotificationManagerBase, "android/app/NotificationManager");
  144. #undef JNI_CLASS_MEMBERS
  145. #if __ANDROID_API__ >= 23
  146. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  147. METHOD (getActiveNotifications, "getActiveNotifications", "()[Landroid/service/notification/StatusBarNotification;")
  148. DECLARE_JNI_CLASS (NotificationManagerApi23, "android/app/NotificationManager");
  149. #undef JNI_CLASS_MEMBERS
  150. #endif
  151. #if __ANDROID_API__ >= 24
  152. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  153. METHOD (areNotificationsEnabled, "areNotificationsEnabled", "()Z")
  154. DECLARE_JNI_CLASS (NotificationManagerApi24, "android/app/NotificationManager");
  155. #undef JNI_CLASS_MEMBERS
  156. #endif
  157. #if __ANDROID_API__ >= 26
  158. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  159. METHOD (createNotificationChannel, "createNotificationChannel", "(Landroid/app/NotificationChannel;)V") \
  160. METHOD (createNotificationChannelGroup, "createNotificationChannelGroup", "(Landroid/app/NotificationChannelGroup;)V")
  161. DECLARE_JNI_CLASS (NotificationManagerApi26, "android/app/NotificationManager");
  162. #undef JNI_CLASS_MEMBERS
  163. #endif
  164. #if __ANDROID_API__ >= 20
  165. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  166. STATICMETHOD (getResultsFromIntent, "getResultsFromIntent", "(Landroid/content/Intent;)Landroid/os/Bundle;")
  167. DECLARE_JNI_CLASS (RemoteInput, "android/app/RemoteInput");
  168. #undef JNI_CLASS_MEMBERS
  169. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  170. METHOD (constructor, "<init>", "(Ljava/lang/String;)V") \
  171. METHOD (build, "build", "()Landroid/app/RemoteInput;") \
  172. METHOD (setAllowFreeFormInput, "setAllowFreeFormInput", "(Z)Landroid/app/RemoteInput$Builder;") \
  173. METHOD (setChoices, "setChoices", "([Ljava/lang/CharSequence;)Landroid/app/RemoteInput$Builder;") \
  174. METHOD (setLabel, "setLabel", "(Ljava/lang/CharSequence;)Landroid/app/RemoteInput$Builder;")
  175. DECLARE_JNI_CLASS (RemoteInputBuilder, "android/app/RemoteInput$Builder");
  176. #undef JNI_CLASS_MEMBERS
  177. #endif
  178. #if __ANDROID_API__ >= 23
  179. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  180. METHOD (getNotification, "getNotification", "()Landroid/app/Notification;")
  181. DECLARE_JNI_CLASS (StatusBarNotification, "android/service/notification/StatusBarNotification");
  182. #undef JNI_CLASS_MEMBERS
  183. #endif
  184. //==========================================================================
  185. #if defined(JUCE_FIREBASE_INSTANCE_ID_SERVICE_CLASSNAME)
  186. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  187. STATICMETHOD (getInstance, "getInstance", "()Lcom/google/firebase/iid/FirebaseInstanceId;") \
  188. METHOD (getToken, "getToken", "()Ljava/lang/String;")
  189. DECLARE_JNI_CLASS (FirebaseInstanceId, "com/google/firebase/iid/FirebaseInstanceId");
  190. #undef JNI_CLASS_MEMBERS
  191. #endif
  192. #if defined(JUCE_FIREBASE_MESSAGING_SERVICE_CLASSNAME)
  193. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  194. STATICMETHOD (getInstance, "getInstance", "()Lcom/google/firebase/messaging/FirebaseMessaging;") \
  195. METHOD (send, "send", "(Lcom/google/firebase/messaging/RemoteMessage;)V") \
  196. METHOD (subscribeToTopic, "subscribeToTopic", "(Ljava/lang/String;)V") \
  197. METHOD (unsubscribeFromTopic, "unsubscribeFromTopic", "(Ljava/lang/String;)V") \
  198. DECLARE_JNI_CLASS (FirebaseMessaging, "com/google/firebase/messaging/FirebaseMessaging");
  199. #undef JNI_CLASS_MEMBERS
  200. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  201. METHOD (getCollapseKey, "getCollapseKey", "()Ljava/lang/String;") \
  202. METHOD (getData, "getData", "()Ljava/util/Map;") \
  203. METHOD (getFrom, "getFrom", "()Ljava/lang/String;") \
  204. METHOD (getMessageId, "getMessageId", "()Ljava/lang/String;") \
  205. METHOD (getMessageType, "getMessageType", "()Ljava/lang/String;") \
  206. METHOD (getNotification, "getNotification", "()Lcom/google/firebase/messaging/RemoteMessage$Notification;") \
  207. METHOD (getSentTime, "getSentTime", "()J") \
  208. METHOD (getTo, "getTo", "()Ljava/lang/String;") \
  209. METHOD (getTtl, "getTtl", "()I")
  210. DECLARE_JNI_CLASS (RemoteMessage, "com/google/firebase/messaging/RemoteMessage");
  211. #undef JNI_CLASS_MEMBERS
  212. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  213. METHOD (addData, "addData", "(Ljava/lang/String;Ljava/lang/String;)Lcom/google/firebase/messaging/RemoteMessage$Builder;") \
  214. METHOD (build, "build", "()Lcom/google/firebase/messaging/RemoteMessage;") \
  215. METHOD (constructor, "<init>", "(Ljava/lang/String;)V") \
  216. METHOD (setCollapseKey, "setCollapseKey", "(Ljava/lang/String;)Lcom/google/firebase/messaging/RemoteMessage$Builder;") \
  217. METHOD (setMessageId, "setMessageId", "(Ljava/lang/String;)Lcom/google/firebase/messaging/RemoteMessage$Builder;") \
  218. METHOD (setMessageType, "setMessageType", "(Ljava/lang/String;)Lcom/google/firebase/messaging/RemoteMessage$Builder;") \
  219. METHOD (setTtl, "setTtl", "(I)Lcom/google/firebase/messaging/RemoteMessage$Builder;")
  220. DECLARE_JNI_CLASS (RemoteMessageBuilder, "com/google/firebase/messaging/RemoteMessage$Builder");
  221. #undef JNI_CLASS_MEMBERS
  222. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD) \
  223. METHOD (getBody, "getBody", "()Ljava/lang/String;") \
  224. METHOD (getBodyLocalizationArgs, "getBodyLocalizationArgs", "()[Ljava/lang/String;") \
  225. METHOD (getBodyLocalizationKey, "getBodyLocalizationKey", "()Ljava/lang/String;") \
  226. METHOD (getClickAction, "getClickAction", "()Ljava/lang/String;") \
  227. METHOD (getColor, "getColor", "()Ljava/lang/String;") \
  228. METHOD (getIcon, "getIcon", "()Ljava/lang/String;") \
  229. METHOD (getLink, "getLink", "()Landroid/net/Uri;") \
  230. METHOD (getSound, "getSound", "()Ljava/lang/String;") \
  231. METHOD (getTag, "getTag", "()Ljava/lang/String;") \
  232. METHOD (getTitle, "getTitle", "()Ljava/lang/String;") \
  233. METHOD (getTitleLocalizationArgs, "getTitleLocalizationArgs", "()[Ljava/lang/String;") \
  234. METHOD (getTitleLocalizationKey, "getTitleLocalizationKey", "()Ljava/lang/String;")
  235. DECLARE_JNI_CLASS (RemoteMessageNotification, "com/google/firebase/messaging/RemoteMessage$Notification");
  236. #undef JNI_CLASS_MEMBERS
  237. #endif
  238. //==============================================================================
  239. bool PushNotifications::Notification::isValid() const noexcept
  240. {
  241. auto* env = getEnv();
  242. bool isValidForPreApi26 = title.isNotEmpty() && body.isNotEmpty() && identifier.isNotEmpty() && icon.isNotEmpty();
  243. bool apiAtLeast26 = env->CallStaticIntMethod (JuceAppActivity, JuceAppActivity.getAndroidSDKVersion) >= 26;
  244. if (apiAtLeast26)
  245. return isValidForPreApi26 && channelId.isNotEmpty();
  246. return isValidForPreApi26;
  247. }
  248. //==========================================================================
  249. struct PushNotifications::Pimpl
  250. {
  251. Pimpl (PushNotifications& p)
  252. : owner (p)
  253. {}
  254. bool areNotificationsEnabled() const
  255. {
  256. #if __ANDROID_API__ >= 24
  257. auto* env = getEnv();
  258. auto notificationManager = getNotificationManager();
  259. if (notificationManager.get() != 0)
  260. return env->CallBooleanMethod (notificationManager, NotificationManagerApi24.areNotificationsEnabled);
  261. return false;
  262. #else
  263. return true;
  264. #endif
  265. }
  266. //==========================================================================
  267. void sendLocalNotification (const PushNotifications::Notification& n)
  268. {
  269. // All required fields have to be setup!
  270. jassert (n.isValid());
  271. auto* env = getEnv();
  272. auto notificationManager = getNotificationManager();
  273. if (notificationManager.get() != 0)
  274. {
  275. auto notification = juceNotificationToJavaNotification (n);
  276. auto tag = javaString (n.identifier);
  277. const int id = 0;
  278. env->CallVoidMethod (notificationManager.get(), NotificationManagerBase.notify, tag.get(), id, notification.get());
  279. }
  280. }
  281. void getDeliveredNotifications() const
  282. {
  283. #if __ANDROID_API__ >= 23
  284. auto* env = getEnv();
  285. Array<PushNotifications::Notification> notifications;
  286. auto notificationManager = getNotificationManager();
  287. jassert (notificationManager.get() != 0);
  288. if (notificationManager.get() != 0)
  289. {
  290. auto statusBarNotifications = LocalRef<jobjectArray> ((jobjectArray)env->CallObjectMethod (notificationManager,
  291. NotificationManagerApi23.getActiveNotifications));
  292. const int numNotifications = env->GetArrayLength (statusBarNotifications.get());
  293. for (int i = 0; i < numNotifications; ++i)
  294. {
  295. auto statusBarNotification = LocalRef<jobject> (env->GetObjectArrayElement (statusBarNotifications.get(), (jsize) i));
  296. auto notification = LocalRef<jobject> (env->CallObjectMethod (statusBarNotification, StatusBarNotification.getNotification));
  297. notifications.add (javaNotificationToJuceNotification (notification));
  298. }
  299. }
  300. owner.listeners.call ([&] (Listener& l) { l.deliveredNotificationsListReceived (notifications); });
  301. #else
  302. // Not supported on this platform
  303. jassertfalse;
  304. owner.listeners.call ([] (Listener& l) { l.deliveredNotificationsListReceived ({}); });
  305. #endif
  306. }
  307. void notifyListenersAboutLocalNotification (const LocalRef<jobject>& intent)
  308. {
  309. auto* env = getEnv();
  310. auto bundle = LocalRef<jobject> (env->CallObjectMethod (intent, AndroidIntent.getExtras));
  311. const auto notification = localNotificationBundleToJuceNotification (bundle);
  312. auto packageName = juceString ((jstring) (android.activity.callObjectMethod (JuceAppActivity.getPackageName)));
  313. String notificationString = packageName + ".JUCE_NOTIFICATION.";
  314. String notificationButtonActionString = packageName + ".JUCE_NOTIFICATION_BUTTON_ACTION.";
  315. String notificationTextInputActionString = packageName + ".JUCE_NOTIFICATION_TEXT_INPUT_ACTION.";
  316. auto actionString = juceString ((jstring) env->CallObjectMethod (intent, AndroidIntent.getAction));
  317. if (actionString.contains (notificationString))
  318. {
  319. owner.listeners.call ([&] (Listener& l) { l.handleNotification (true, notification); });
  320. }
  321. else if (actionString.contains (notificationButtonActionString))
  322. {
  323. auto prefix = notificationButtonActionString + notification.identifier + ".";
  324. auto actionTitle = actionString.fromLastOccurrenceOf (prefix, false, false) // skip prefix
  325. .fromFirstOccurrenceOf (".", false, false); // skip action index
  326. owner.listeners.call ([&] (Listener& l) { l.handleNotificationAction (true, notification, actionTitle, {}); });
  327. }
  328. #if __ANDROID_API__ >= 20
  329. else if (actionString.contains (notificationTextInputActionString))
  330. {
  331. auto prefix = notificationTextInputActionString + notification.identifier + ".";
  332. auto actionTitle = actionString.fromLastOccurrenceOf (prefix, false, false) // skip prefix
  333. .fromFirstOccurrenceOf (".", false, false); // skip action index
  334. auto actionIndex = actionString.fromLastOccurrenceOf (prefix, false, false).upToFirstOccurrenceOf (".", false, false);
  335. auto resultKeyString = javaString (actionTitle + actionIndex);
  336. auto remoteInputResult = LocalRef<jobject> (env->CallStaticObjectMethod (RemoteInput, RemoteInput.getResultsFromIntent, intent.get()));
  337. String responseString;
  338. if (remoteInputResult.get() != 0)
  339. {
  340. auto charSequence = LocalRef<jobject> (env->CallObjectMethod (remoteInputResult, JavaBundle.getCharSequence, resultKeyString.get()));
  341. auto responseStringRef = LocalRef<jstring> ((jstring) env->CallObjectMethod (charSequence, JavaCharSequence.toString));
  342. responseString = juceString (responseStringRef.get());
  343. }
  344. owner.listeners.call ([&] (Listener& l) { l.handleNotificationAction (true, notification, actionTitle, responseString); });
  345. }
  346. #endif
  347. }
  348. void notifyListenersAboutLocalNotificationDeleted (const LocalRef<jobject>& intent)
  349. {
  350. auto* env = getEnv();
  351. auto bundle = LocalRef<jobject> (env->CallObjectMethod (intent, AndroidIntent.getExtras));
  352. auto notification = localNotificationBundleToJuceNotification (bundle);
  353. owner.listeners.call ([&] (Listener& l) { l.localNotificationDismissedByUser (notification); });
  354. }
  355. void removeAllDeliveredNotifications()
  356. {
  357. auto* env = getEnv();
  358. auto notificationManager = getNotificationManager();
  359. if (notificationManager.get() != 0)
  360. env->CallVoidMethod (notificationManager.get(), NotificationManagerBase.cancelAll);
  361. }
  362. void removeDeliveredNotification (const String& identifier)
  363. {
  364. auto* env = getEnv();
  365. auto notificationManager = getNotificationManager();
  366. if (notificationManager.get() != 0)
  367. {
  368. auto tag = javaString (identifier);
  369. const int id = 0;
  370. env->CallVoidMethod (notificationManager.get(), NotificationManagerBase.cancel, tag.get(), id);
  371. }
  372. }
  373. //==========================================================================
  374. String getDeviceToken() const
  375. {
  376. #if defined(JUCE_FIREBASE_INSTANCE_ID_SERVICE_CLASSNAME)
  377. auto* env = getEnv();
  378. auto instanceId = LocalRef<jobject> (env->CallStaticObjectMethod (FirebaseInstanceId, FirebaseInstanceId.getInstance));
  379. return juceString ((jstring) env->CallObjectMethod (instanceId, FirebaseInstanceId.getToken));
  380. #else
  381. return {};
  382. #endif
  383. }
  384. void notifyListenersTokenRefreshed (const String& token)
  385. {
  386. #if defined(JUCE_FIREBASE_INSTANCE_ID_SERVICE_CLASSNAME)
  387. MessageManager::callAsync ([this, token]
  388. {
  389. owner.listeners.call ([&] (Listener& l) { l.deviceTokenRefreshed (token); });
  390. });
  391. #else
  392. ignoreUnused (token);
  393. #endif
  394. }
  395. void subscribeToTopic (const String& topic)
  396. {
  397. #if defined(JUCE_FIREBASE_MESSAGING_SERVICE_CLASSNAME)
  398. auto* env = getEnv();
  399. auto firebaseMessaging = LocalRef<jobject> (env->CallStaticObjectMethod (FirebaseMessaging,
  400. FirebaseMessaging.getInstance));
  401. env->CallVoidMethod (firebaseMessaging, FirebaseMessaging.subscribeToTopic, javaString (topic).get());
  402. #else
  403. ignoreUnused (topic);
  404. #endif
  405. }
  406. void unsubscribeFromTopic (const String& topic)
  407. {
  408. #if defined(JUCE_FIREBASE_MESSAGING_SERVICE_CLASSNAME)
  409. auto* env = getEnv();
  410. auto firebaseMessaging = LocalRef<jobject> (env->CallStaticObjectMethod (FirebaseMessaging,
  411. FirebaseMessaging.getInstance));
  412. env->CallVoidMethod (firebaseMessaging, FirebaseMessaging.unsubscribeFromTopic, javaString (topic).get());
  413. #else
  414. ignoreUnused (topic);
  415. #endif
  416. }
  417. void sendUpstreamMessage (const String& serverSenderId,
  418. const String& collapseKey,
  419. const String& messageId,
  420. const String& messageType,
  421. int timeToLive,
  422. const StringPairArray& additionalData)
  423. {
  424. #if defined(JUCE_FIREBASE_MESSAGING_SERVICE_CLASSNAME)
  425. auto* env = getEnv();
  426. auto messageBuilder = LocalRef<jobject> (env->NewObject (RemoteMessageBuilder,
  427. RemoteMessageBuilder.constructor,
  428. javaString (serverSenderId + "@gcm_googleapis.com").get()));
  429. env->CallObjectMethod (messageBuilder, RemoteMessageBuilder.setCollapseKey, javaString (collapseKey).get());
  430. env->CallObjectMethod (messageBuilder, RemoteMessageBuilder.setMessageId, javaString (messageId).get());
  431. env->CallObjectMethod (messageBuilder, RemoteMessageBuilder.setMessageType, javaString (messageType).get());
  432. env->CallObjectMethod (messageBuilder, RemoteMessageBuilder.setTtl, timeToLive);
  433. auto keys = additionalData.getAllKeys();
  434. for (const auto& key : keys)
  435. env->CallObjectMethod (messageBuilder,
  436. RemoteMessageBuilder.addData,
  437. javaString (key).get(),
  438. javaString (additionalData[key]).get());
  439. auto message = LocalRef<jobject> (env->CallObjectMethod (messageBuilder, RemoteMessageBuilder.build));
  440. auto firebaseMessaging = LocalRef<jobject> (env->CallStaticObjectMethod (FirebaseMessaging,
  441. FirebaseMessaging.getInstance));
  442. env->CallVoidMethod (firebaseMessaging, FirebaseMessaging.send, message.get());
  443. #else
  444. ignoreUnused (serverSenderId, collapseKey, messageId, messageType);
  445. ignoreUnused (timeToLive, additionalData);
  446. #endif
  447. }
  448. void notifyListenersAboutRemoteNotificationFromSystemTray (const LocalRef<jobject>& intent)
  449. {
  450. #if defined(JUCE_FIREBASE_MESSAGING_SERVICE_CLASSNAME)
  451. auto* env = getEnv();
  452. auto bundle = LocalRef<jobject> (env->CallObjectMethod (intent, AndroidIntent.getExtras));
  453. auto notification = remoteNotificationBundleToJuceNotification (bundle);
  454. owner.listeners.call ([&] (Listener& l) { l.handleNotification (false, notification); });
  455. #else
  456. ignoreUnused (intent);
  457. #endif
  458. }
  459. void notifyListenersAboutRemoteNotificationFromService (const LocalRef<jobject>& remoteNotification)
  460. {
  461. #if defined(JUCE_FIREBASE_MESSAGING_SERVICE_CLASSNAME)
  462. GlobalRef rn (remoteNotification.get());
  463. MessageManager::callAsync ([this, rn]
  464. {
  465. auto notification = firebaseRemoteNotificationToJuceNotification (rn.get());
  466. owner.listeners.call ([&] (Listener& l) { l.handleNotification (false, notification); });
  467. });
  468. #else
  469. ignoreUnused (remoteNotification);
  470. #endif
  471. }
  472. void notifyListenersAboutRemoteNotificationsDeleted()
  473. {
  474. #if defined(JUCE_FIREBASE_MESSAGING_SERVICE_CLASSNAME)
  475. MessageManager::callAsync ([this]
  476. {
  477. owner.listeners.call ([] (Listener& l) { l.remoteNotificationsDeleted(); });
  478. });
  479. #endif
  480. }
  481. void notifyListenersAboutUpstreamMessageSent (const LocalRef<jstring>& messageId)
  482. {
  483. #if defined(JUCE_FIREBASE_MESSAGING_SERVICE_CLASSNAME)
  484. GlobalRef mid (messageId);
  485. MessageManager::callAsync ([this, mid]
  486. {
  487. auto midString = juceString ((jstring) mid.get());
  488. owner.listeners.call ([&] (Listener& l) { l.upstreamMessageSent (midString); });
  489. });
  490. #else
  491. ignoreUnused (messageId);
  492. #endif
  493. }
  494. void notifyListenersAboutUpstreamMessageSendingError (const LocalRef<jstring>& messageId,
  495. const LocalRef<jstring>& error)
  496. {
  497. #if defined(JUCE_FIREBASE_MESSAGING_SERVICE_CLASSNAME)
  498. GlobalRef mid (messageId), e (error);
  499. MessageManager::callAsync ([this, mid, e]
  500. {
  501. auto midString = juceString ((jstring) mid.get());
  502. auto eString = juceString ((jstring) e.get());
  503. owner.listeners.call ([&] (Listener& l) { l.upstreamMessageSendingError (midString, eString); });
  504. });
  505. #else
  506. ignoreUnused (messageId, error);
  507. #endif
  508. }
  509. static LocalRef<jobject> getNotificationManager()
  510. {
  511. auto* env = getEnv();
  512. return LocalRef<jobject> (env->CallObjectMethod (android.activity,
  513. JuceAppActivity.getSystemService,
  514. javaString ("notification").get()));
  515. }
  516. static LocalRef<jobject> juceNotificationToJavaNotification (const PushNotifications::Notification& n)
  517. {
  518. auto* env = getEnv();
  519. auto notificationBuilder = createNotificationBuilder (n);
  520. setupRequiredFields (n, notificationBuilder);
  521. setupOptionalFields (n, notificationBuilder);
  522. if (n.actions.size() > 0)
  523. setupActions (n, notificationBuilder);
  524. #if __ANDROID_API__ >= 16
  525. return LocalRef<jobject> (env->CallObjectMethod (notificationBuilder, NotificationBuilderApi16.build));
  526. #else
  527. return LocalRef<jobject> (env->CallObjectMethod (notificationBuilder, NotificationBuilderBase.getNotification));
  528. #endif
  529. }
  530. static LocalRef<jobject> createNotificationBuilder (const PushNotifications::Notification& n)
  531. {
  532. auto* env = getEnv();
  533. jclass builderClass = env->FindClass ("android/app/Notification$Builder");
  534. jassert (builderClass != 0);
  535. if (builderClass == 0)
  536. return LocalRef<jobject> (0);
  537. jmethodID builderConstructor = 0;
  538. const bool apiAtLeast26 = env->CallStaticIntMethod (JuceAppActivity, JuceAppActivity.getAndroidSDKVersion) >= 26;
  539. if (apiAtLeast26)
  540. builderConstructor = env->GetMethodID (builderClass, "<init>", "(Landroid/content/Context;Ljava/lang/String;)V");
  541. else
  542. builderConstructor = env->GetMethodID (builderClass, "<init>", "(Landroid/content/Context;)V");
  543. jassert (builderConstructor != 0);
  544. if (builderConstructor == 0)
  545. return LocalRef<jobject> (0);
  546. if (apiAtLeast26)
  547. return LocalRef<jobject> (env->NewObject (builderClass, builderConstructor,
  548. android.activity.get(), javaString (n.channelId).get()));
  549. return LocalRef<jobject> (env->NewObject (builderClass, builderConstructor, android.activity.get()));
  550. }
  551. static void setupRequiredFields (const PushNotifications::Notification& n, LocalRef<jobject>& notificationBuilder)
  552. {
  553. auto* env = getEnv();
  554. auto activityClass = LocalRef<jobject> (env->CallObjectMethod (android.activity, JavaObject.getClass));
  555. auto notifyIntent = LocalRef<jobject> (env->NewObject (AndroidIntent, AndroidIntent.constructorWithContextAndClass, android.activity.get(), activityClass.get()));
  556. auto packageNameString = LocalRef<jstring> ((jstring) (android.activity.callObjectMethod (JuceAppActivity.getPackageName)));
  557. auto actionStringSuffix = javaString (".JUCE_NOTIFICATION." + n.identifier);
  558. auto actionString = LocalRef<jstring> ((jstring)env->CallObjectMethod (packageNameString, JavaString.concat, actionStringSuffix.get()));
  559. env->CallObjectMethod (notifyIntent, AndroidIntent.setAction, actionString.get());
  560. // Packaging entire notification into extras bundle here, so that we can retrieve all the details later on
  561. env->CallObjectMethod (notifyIntent, AndroidIntent.putExtras, juceNotificationToBundle (n).get());
  562. auto notifyPendingIntent = LocalRef<jobject> (env->CallStaticObjectMethod (AndroidPendingIntent,
  563. AndroidPendingIntent.getActivity,
  564. android.activity.get(),
  565. 1002,
  566. notifyIntent.get(),
  567. 0));
  568. env->CallObjectMethod (notificationBuilder, NotificationBuilderBase.setContentTitle, javaString (n.title).get());
  569. env->CallObjectMethod (notificationBuilder, NotificationBuilderBase.setContentText, javaString (n.body).get());
  570. env->CallObjectMethod (notificationBuilder, NotificationBuilderBase.setContentIntent, notifyPendingIntent.get());
  571. auto resources = LocalRef<jobject> (env->CallObjectMethod (android.activity, JuceAppActivity.getResources));
  572. const int iconId = env->CallIntMethod (resources, AndroidResources.getIdentifier, javaString (n.icon).get(),
  573. javaString ("raw").get(), packageNameString.get());
  574. env->CallObjectMethod (notificationBuilder, NotificationBuilderBase.setSmallIcon, iconId);
  575. #if __ANDROID_API__ >= 21
  576. if (n.publicVersion != nullptr)
  577. {
  578. // Public version of a notification is not expected to have another public one!
  579. jassert (n.publicVersion->publicVersion == nullptr);
  580. auto publicNotificationBuilder = createNotificationBuilder (n);
  581. setupRequiredFields (*n.publicVersion, publicNotificationBuilder);
  582. setupOptionalFields (*n.publicVersion, publicNotificationBuilder);
  583. auto publicVersion = LocalRef<jobject> (env->CallObjectMethod (publicNotificationBuilder, NotificationBuilderApi16.build));
  584. env->CallObjectMethod (notificationBuilder, NotificationBuilderApi21.setPublicVersion, publicVersion.get());
  585. }
  586. #endif
  587. }
  588. static LocalRef<jobject> juceNotificationToBundle (const PushNotifications::Notification& n)
  589. {
  590. auto* env = getEnv();
  591. auto bundle = LocalRef<jobject> (env->NewObject (JavaBundle, JavaBundle.constructor));
  592. env->CallVoidMethod (bundle, JavaBundle.putString, javaString ("identifier") .get(), javaString (n.identifier).get());
  593. env->CallVoidMethod (bundle, JavaBundle.putString, javaString ("title") .get(), javaString (n.title).get());
  594. env->CallVoidMethod (bundle, JavaBundle.putString, javaString ("body") .get(), javaString (n.body).get());
  595. env->CallVoidMethod (bundle, JavaBundle.putString, javaString ("subtitle") .get(), javaString (n.subtitle).get());
  596. env->CallVoidMethod (bundle, JavaBundle.putInt, javaString ("badgeNumber") .get(), n.badgeNumber);
  597. env->CallVoidMethod (bundle, JavaBundle.putString, javaString ("soundToPlay") .get(), javaString (n.soundToPlay.toString (true)).get());
  598. env->CallVoidMethod (bundle, JavaBundle.putBundle, javaString ("properties") .get(), varToBundleWithPropertiesString (n.properties).get());
  599. env->CallVoidMethod (bundle, JavaBundle.putString, javaString ("icon") .get(), javaString (n.icon).get());
  600. env->CallVoidMethod (bundle, JavaBundle.putString, javaString ("channelId") .get(), javaString (n.channelId).get());
  601. env->CallVoidMethod (bundle, JavaBundle.putString, javaString ("tickerText") .get(), javaString (n.tickerText).get());
  602. env->CallVoidMethod (bundle, JavaBundle.putInt, javaString ("progressMax") .get(), n.progress.max);
  603. env->CallVoidMethod (bundle, JavaBundle.putInt, javaString ("progressCurrent") .get(), n.progress.current);
  604. env->CallVoidMethod (bundle, JavaBundle.putBoolean, javaString ("progressIndeterminate") .get(), n.progress.indeterminate);
  605. env->CallVoidMethod (bundle, JavaBundle.putString, javaString ("person") .get(), javaString (n.person).get());
  606. env->CallVoidMethod (bundle, JavaBundle.putInt, javaString ("type") .get(), n.type);
  607. env->CallVoidMethod (bundle, JavaBundle.putInt, javaString ("priority") .get(), n.priority);
  608. env->CallVoidMethod (bundle, JavaBundle.putInt, javaString ("lockScreenAppearance") .get(), n.lockScreenAppearance);
  609. env->CallVoidMethod (bundle, JavaBundle.putString, javaString ("groupId") .get(), javaString (n.groupId).get());
  610. env->CallVoidMethod (bundle, JavaBundle.putString, javaString ("groupSortKey") .get(), javaString (n.groupSortKey).get());
  611. env->CallVoidMethod (bundle, JavaBundle.putBoolean, javaString ("groupSummary") .get(), n.groupSummary);
  612. env->CallVoidMethod (bundle, JavaBundle.putInt, javaString ("accentColour") .get(), n.accentColour.getARGB());
  613. env->CallVoidMethod (bundle, JavaBundle.putInt, javaString ("ledColour") .get(), n.ledColour.getARGB());
  614. env->CallVoidMethod (bundle, JavaBundle.putInt, javaString ("ledBlinkPatternMsToBeOn") .get(), n.ledBlinkPattern.msToBeOn);
  615. env->CallVoidMethod (bundle, JavaBundle.putInt, javaString ("ledBlinkPatternMsToBeOff").get(), n.ledBlinkPattern.msToBeOff);
  616. env->CallVoidMethod (bundle, JavaBundle.putBoolean, javaString ("shouldAutoCancel") .get(), n.shouldAutoCancel);
  617. env->CallVoidMethod (bundle, JavaBundle.putBoolean, javaString ("localOnly") .get(), n.localOnly);
  618. env->CallVoidMethod (bundle, JavaBundle.putBoolean, javaString ("ongoing") .get(), n.ongoing);
  619. env->CallVoidMethod (bundle, JavaBundle.putBoolean, javaString ("alertOnlyOnce") .get(), n.alertOnlyOnce);
  620. env->CallVoidMethod (bundle, JavaBundle.putInt, javaString ("timestampVisibility") .get(), n.timestampVisibility);
  621. env->CallVoidMethod (bundle, JavaBundle.putInt, javaString ("badgeIconType") .get(), n.badgeIconType);
  622. env->CallVoidMethod (bundle, JavaBundle.putInt, javaString ("groupAlertBehaviour") .get(), n.groupAlertBehaviour);
  623. env->CallVoidMethod (bundle, JavaBundle.putLong, javaString ("timeoutAfterMs") .get(), (jlong)n.timeoutAfterMs);
  624. const int size = n.vibrationPattern.size();
  625. if (size > 0)
  626. {
  627. auto array = LocalRef<jlongArray> (env->NewLongArray (size));
  628. jlong* elements = env->GetLongArrayElements (array, 0);
  629. for (int i = 0; i < size; ++i)
  630. elements[i] = (jlong) n.vibrationPattern[i];
  631. env->SetLongArrayRegion (array, 0, size, elements);
  632. env->CallVoidMethod (bundle, JavaBundle.putLongArray, javaString ("vibrationPattern").get(), array.get());
  633. }
  634. return bundle;
  635. }
  636. static void setupOptionalFields (const PushNotifications::Notification& n, LocalRef<jobject>& notificationBuilder)
  637. {
  638. auto* env = getEnv();
  639. if (n.subtitle.isNotEmpty())
  640. env->CallObjectMethod (notificationBuilder, NotificationBuilderBase.setContentInfo, javaString (n.subtitle).get());
  641. auto soundName = n.soundToPlay.toString (true);
  642. if (soundName == "default_os_sound")
  643. {
  644. const int playDefaultSound = 1;
  645. env->CallObjectMethod (notificationBuilder, NotificationBuilderBase.setDefaults, playDefaultSound);
  646. }
  647. else if (! soundName.isEmpty())
  648. {
  649. env->CallObjectMethod (notificationBuilder, NotificationBuilderBase.setSound, juceUrlToAndroidUri (n.soundToPlay).get());
  650. }
  651. if (n.largeIcon.isValid())
  652. env->CallObjectMethod (notificationBuilder, NotificationBuilderBase.setLargeIcon, imagetoJavaBitmap (n.largeIcon).get());
  653. if (n.tickerText.isNotEmpty())
  654. env->CallObjectMethod (notificationBuilder, NotificationBuilderBase.setTicker, javaString (n.tickerText).get());
  655. if (n.ledColour != Colour())
  656. {
  657. env->CallObjectMethod (notificationBuilder,
  658. NotificationBuilderBase.setLights,
  659. n.ledColour.getARGB(),
  660. n.ledBlinkPattern.msToBeOn,
  661. n.ledBlinkPattern.msToBeOff);
  662. }
  663. if (! n.vibrationPattern.isEmpty())
  664. {
  665. const int size = n.vibrationPattern.size();
  666. if (size > 0)
  667. {
  668. auto array = LocalRef<jlongArray> (env->NewLongArray (size));
  669. jlong* elements = env->GetLongArrayElements (array, 0);
  670. for (int i = 0; i < size; ++i)
  671. elements[i] = (jlong) n.vibrationPattern[i];
  672. env->SetLongArrayRegion (array, 0, size, elements);
  673. env->CallObjectMethod (notificationBuilder, NotificationBuilderBase.setVibrate, array.get());
  674. }
  675. }
  676. env->CallObjectMethod (notificationBuilder, NotificationBuilderBase.setProgress, n.progress.max, n.progress.current, n.progress.indeterminate);
  677. env->CallObjectMethod (notificationBuilder, NotificationBuilderBase.setNumber, n.badgeNumber);
  678. env->CallObjectMethod (notificationBuilder, NotificationBuilderBase.setAutoCancel, n.shouldAutoCancel);
  679. env->CallObjectMethod (notificationBuilder, NotificationBuilderBase.setOngoing, n.ongoing);
  680. env->CallObjectMethod (notificationBuilder, NotificationBuilderBase.setOnlyAlertOnce, n.alertOnlyOnce);
  681. #if __ANDROID_API__ >= 16
  682. if (n.subtitle.isNotEmpty())
  683. env->CallObjectMethod (notificationBuilder, NotificationBuilderApi16.setSubText, javaString (n.subtitle).get());
  684. env->CallObjectMethod (notificationBuilder, NotificationBuilderApi16.setPriority, n.priority);
  685. #if __ANDROID_API__ < 24
  686. const bool useChronometer = n.timestampVisibility == PushNotifications::Notification::chronometer;
  687. env->CallObjectMethod (notificationBuilder, NotificationBuilderApi16.setUsesChronometer, useChronometer);
  688. #endif
  689. #endif
  690. #if __ANDROID_API__ >= 17
  691. const bool showTimeStamp = n.timestampVisibility != PushNotifications::Notification::off;
  692. env->CallObjectMethod (notificationBuilder, NotificationBuilderApi17.setShowWhen, showTimeStamp);
  693. #endif
  694. #if __ANDROID_API__ >= 20
  695. if (n.groupId.isNotEmpty())
  696. {
  697. env->CallObjectMethod (notificationBuilder, NotificationBuilderApi20.setGroup, javaString (n.groupId).get());
  698. env->CallObjectMethod (notificationBuilder, NotificationBuilderApi20.setGroupSummary, n.groupSummary);
  699. }
  700. if (n.groupSortKey.isNotEmpty())
  701. env->CallObjectMethod (notificationBuilder, NotificationBuilderApi20.setSortKey, javaString (n.groupSortKey).get());
  702. env->CallObjectMethod (notificationBuilder, NotificationBuilderApi20.setLocalOnly, n.localOnly);
  703. auto extras = LocalRef<jobject> (env->NewObject (JavaBundle, JavaBundle.constructor));
  704. env->CallVoidMethod (extras, JavaBundle.putBundle, javaString ("notificationData").get(),
  705. juceNotificationToBundle (n).get());
  706. env->CallObjectMethod (notificationBuilder, NotificationBuilderApi20.addExtras, extras.get());
  707. #endif
  708. #if __ANDROID_API__ >= 21
  709. if (n.person.isNotEmpty())
  710. env->CallObjectMethod (notificationBuilder, NotificationBuilderApi21.addPerson, javaString (n.person).get());
  711. auto categoryString = typeToCategory (n.type);
  712. if (categoryString.isNotEmpty())
  713. env->CallObjectMethod (notificationBuilder, NotificationBuilderApi21.setCategory, javaString (categoryString).get());
  714. if (n.accentColour != Colour())
  715. env->CallObjectMethod (notificationBuilder, NotificationBuilderApi21.setColor, n.accentColour.getARGB());
  716. env->CallObjectMethod (notificationBuilder, NotificationBuilderApi21.setVisibility, n.lockScreenAppearance);
  717. #endif
  718. #if __ANDROID_API__ >= 24
  719. const bool useChronometer = n.timestampVisibility == PushNotifications::Notification::chronometer;
  720. const bool useCountDownChronometer = n.timestampVisibility == PushNotifications::Notification::countDownChronometer;
  721. env->CallObjectMethod (notificationBuilder, NotificationBuilderApi24.setChronometerCountDown, useCountDownChronometer);
  722. env->CallObjectMethod (notificationBuilder, NotificationBuilderApi16.setUsesChronometer, useChronometer | useCountDownChronometer);
  723. #endif
  724. #if __ANDROID_API__ >= 26
  725. env->CallObjectMethod (notificationBuilder, NotificationBuilderApi26.setBadgeIconType, n.badgeIconType);
  726. env->CallObjectMethod (notificationBuilder, NotificationBuilderApi26.setGroupAlertBehavior, n.groupAlertBehaviour);
  727. env->CallObjectMethod (notificationBuilder, NotificationBuilderApi26.setTimeoutAfter, (jlong) n.timeoutAfterMs);
  728. #endif
  729. setupNotificationDeletedCallback (n, notificationBuilder);
  730. }
  731. static void setupNotificationDeletedCallback (const PushNotifications::Notification& n,
  732. LocalRef<jobject>& notificationBuilder)
  733. {
  734. auto* env = getEnv();
  735. auto activityClass = LocalRef<jobject> (env->CallObjectMethod (android.activity, JavaObject.getClass));
  736. auto deleteIntent = LocalRef<jobject> (env->NewObject (AndroidIntent, AndroidIntent.constructorWithContextAndClass, android.activity.get(), activityClass.get()));
  737. auto packageNameString = LocalRef<jstring> ((jstring) (android.activity.callObjectMethod (JuceAppActivity.getPackageName)));
  738. auto actionStringSuffix = javaString (".JUCE_NOTIFICATION_DELETED." + n.identifier);
  739. auto actionString = LocalRef<jstring> ((jstring)env->CallObjectMethod (packageNameString, JavaString.concat, actionStringSuffix.get()));
  740. env->CallObjectMethod (deleteIntent, AndroidIntent.setAction, actionString.get());
  741. env->CallObjectMethod (deleteIntent, AndroidIntent.putExtras, juceNotificationToBundle (n).get());
  742. auto deletePendingIntent = LocalRef<jobject> (env->CallStaticObjectMethod (AndroidPendingIntent,
  743. AndroidPendingIntent.getActivity,
  744. android.activity.get(),
  745. 1002,
  746. deleteIntent.get(),
  747. 0));
  748. env->CallObjectMethod (notificationBuilder, NotificationBuilderBase.setDeleteIntent, deletePendingIntent.get());
  749. }
  750. static void setupActions (const PushNotifications::Notification& n, LocalRef<jobject>& notificationBuilder)
  751. {
  752. #if __ANDROID_API__ >= 16
  753. auto* env = getEnv();
  754. int actionIndex = 0;
  755. for (const auto& action : n.actions)
  756. {
  757. auto activityClass = LocalRef<jobject> (env->CallObjectMethod (android.activity, JavaObject.getClass));
  758. auto notifyIntent = LocalRef<jobject> (env->NewObject (AndroidIntent, AndroidIntent.constructorWithContextAndClass, android.activity.get(), activityClass.get()));
  759. const bool isTextStyle = action.style == PushNotifications::Notification::Action::text;
  760. auto packageNameString = LocalRef<jstring> ((jstring) (android.activity.callObjectMethod (JuceAppActivity.getPackageName)));
  761. const String notificationActionString = isTextStyle ? ".JUCE_NOTIFICATION_TEXT_INPUT_ACTION." : ".JUCE_NOTIFICATION_BUTTON_ACTION.";
  762. auto actionStringSuffix = javaString (notificationActionString + n.identifier + "." + String (actionIndex) + "." + action.title);
  763. auto actionString = LocalRef<jstring> ((jstring)env->CallObjectMethod (packageNameString, JavaString.concat, actionStringSuffix.get()));
  764. env->CallObjectMethod (notifyIntent, AndroidIntent.setAction, actionString.get());
  765. // Packaging entire notification into extras bundle here, so that we can retrieve all the details later on
  766. env->CallObjectMethod (notifyIntent, AndroidIntent.putExtras, juceNotificationToBundle (n).get());
  767. auto notifyPendingIntent = LocalRef<jobject> (env->CallStaticObjectMethod (AndroidPendingIntent,
  768. AndroidPendingIntent.getActivity,
  769. android.activity.get(),
  770. 1002,
  771. notifyIntent.get(),
  772. 0));
  773. auto resources = LocalRef<jobject> (env->CallObjectMethod (android.activity, JuceAppActivity.getResources));
  774. int iconId = env->CallIntMethod (resources, AndroidResources.getIdentifier, javaString (action.icon).get(),
  775. javaString ("raw").get(), packageNameString.get());
  776. if (iconId == 0)
  777. iconId = env->CallIntMethod (resources, AndroidResources.getIdentifier, javaString (n.icon).get(),
  778. javaString ("raw").get(), packageNameString.get());
  779. #if __ANDROID_API__ >= 20
  780. auto actionBuilder = LocalRef<jobject> (env->NewObject (NotificationActionBuilder,
  781. NotificationActionBuilder.constructor,
  782. iconId,
  783. javaString (action.title).get(),
  784. notifyPendingIntent.get()));
  785. env->CallObjectMethod (actionBuilder, NotificationActionBuilder.addExtras,
  786. varToBundleWithPropertiesString (action.parameters).get());
  787. if (isTextStyle)
  788. {
  789. auto resultKey = javaString (action.title + String (actionIndex));
  790. auto remoteInputBuilder = LocalRef<jobject> (env->NewObject (RemoteInputBuilder,
  791. RemoteInputBuilder.constructor,
  792. resultKey.get()));
  793. if (! action.textInputPlaceholder.isEmpty())
  794. env->CallObjectMethod (remoteInputBuilder, RemoteInputBuilder.setLabel, javaString (action.textInputPlaceholder).get());
  795. if (! action.allowedResponses.isEmpty())
  796. {
  797. env->CallObjectMethod (remoteInputBuilder, RemoteInputBuilder.setAllowFreeFormInput, false);
  798. const int size = action.allowedResponses.size();
  799. auto array = LocalRef<jobjectArray> (env->NewObjectArray (size, env->FindClass ("java/lang/String"), 0));
  800. for (int i = 0; i < size; ++i)
  801. {
  802. const auto& response = action.allowedResponses[i];
  803. auto responseString = javaString (response);
  804. env->SetObjectArrayElement (array, i, responseString.get());
  805. }
  806. env->CallObjectMethod (remoteInputBuilder, RemoteInputBuilder.setChoices, array.get());
  807. }
  808. env->CallObjectMethod (actionBuilder, NotificationActionBuilder.addRemoteInput,
  809. env->CallObjectMethod (remoteInputBuilder, RemoteInputBuilder.build));
  810. }
  811. env->CallObjectMethod (notificationBuilder, NotificationBuilderApi20.addAction,
  812. env->CallObjectMethod (actionBuilder, NotificationActionBuilder.build));
  813. #else
  814. env->CallObjectMethod (notificationBuilder, NotificationBuilderApi16.addAction,
  815. iconId, javaString (action.title).get(), notifyPendingIntent.get());
  816. #endif
  817. ++actionIndex;
  818. }
  819. #else
  820. ignoreUnused (n, notificationBuilder);
  821. #endif // #if __ANDROID_API__ >= 16
  822. }
  823. static LocalRef<jobject> juceUrlToAndroidUri (const URL& url)
  824. {
  825. auto* env = getEnv();
  826. auto packageNameString = LocalRef<jstring> ((jstring) (android.activity.callObjectMethod (JuceAppActivity.getPackageName)));
  827. auto resources = LocalRef<jobject> (env->CallObjectMethod (android.activity, JuceAppActivity.getResources));
  828. const int id = env->CallIntMethod (resources, AndroidResources.getIdentifier, javaString (url.toString (true)).get(),
  829. javaString ("raw").get(), packageNameString.get());
  830. auto schemeString = javaString ("android.resource://");
  831. auto resourceString = javaString ("/" + String (id));
  832. auto uriString = LocalRef<jstring> ((jstring) env->CallObjectMethod (schemeString, JavaString.concat, packageNameString.get()));
  833. uriString = LocalRef<jstring> ((jstring) env->CallObjectMethod (uriString, JavaString.concat, resourceString.get()));
  834. return LocalRef<jobject> (env->CallStaticObjectMethod (AndroidUri, AndroidUri.parse, uriString.get()));
  835. }
  836. static LocalRef<jobject> imagetoJavaBitmap (const Image& image)
  837. {
  838. auto* env = getEnv();
  839. Image imageToUse = image.convertedToFormat (Image::PixelFormat::ARGB);
  840. auto bitmapConfig = LocalRef<jobject> (env->CallStaticObjectMethod (AndroidBitmapConfig,
  841. AndroidBitmapConfig.valueOf,
  842. javaString ("ARGB_8888").get()));
  843. auto bitmap = LocalRef<jobject> (env->CallStaticObjectMethod (AndroidBitmap,
  844. AndroidBitmap.createBitmap,
  845. image.getWidth(),
  846. image.getHeight(),
  847. bitmapConfig.get()));
  848. for (int i = 0; i < image.getWidth(); ++i)
  849. for (int j = 0; j < image.getHeight(); ++j)
  850. env->CallVoidMethod (bitmap.get(), AndroidBitmap.setPixel, i, j, image.getPixelAt (i, j).getARGB());
  851. return bitmap;
  852. }
  853. static String typeToCategory (PushNotifications::Notification::Type t)
  854. {
  855. switch (t)
  856. {
  857. case PushNotifications::Notification::unspecified: return {};
  858. case PushNotifications::Notification::alarm: return "alarm";
  859. case PushNotifications::Notification::call: return "call";
  860. case PushNotifications::Notification::email: return "email";
  861. case PushNotifications::Notification::error: return "err";
  862. case PushNotifications::Notification::event: return "event";
  863. case PushNotifications::Notification::message: return "msg";
  864. case PushNotifications::Notification::taskProgress: return "progress";
  865. case PushNotifications::Notification::promo: return "promo";
  866. case PushNotifications::Notification::recommendation: return "recommendation";
  867. case PushNotifications::Notification::reminder: return "reminder";
  868. case PushNotifications::Notification::service: return "service";
  869. case PushNotifications::Notification::social: return "social";
  870. case PushNotifications::Notification::status: return "status";
  871. case PushNotifications::Notification::system: return "sys";
  872. case PushNotifications::Notification::transport: return "transport";
  873. }
  874. return {};
  875. }
  876. static LocalRef<jobject> varToBundleWithPropertiesString (const var& varToParse)
  877. {
  878. auto* env = getEnv();
  879. auto bundle = LocalRef<jobject> (env->NewObject (JavaBundle, JavaBundle.constructor));
  880. env->CallVoidMethod (bundle, JavaBundle.putString, javaString ("properties").get(),
  881. javaString (JSON::toString (varToParse, false)).get());
  882. return bundle;
  883. }
  884. // Gets "properties" var from bundle.
  885. static var bundleWithPropertiesStringToVar (const LocalRef<jobject>& bundle)
  886. {
  887. auto* env = getEnv();
  888. auto varString = LocalRef<jstring> ((jstring)env->CallObjectMethod (bundle, JavaBundle.getString,
  889. javaString ("properties").get()));
  890. var resultVar;
  891. JSON::parse (juceString (varString.get()), resultVar);
  892. // Note: we are not checking if result of parsing was okay, because there may be no properties set at all.
  893. return resultVar;
  894. }
  895. // Reverse of juceNotificationToBundle().
  896. static PushNotifications::Notification localNotificationBundleToJuceNotification (const LocalRef<jobject>& bundle)
  897. {
  898. auto* env = getEnv();
  899. PushNotifications::Notification n;
  900. if (bundle.get() != 0)
  901. {
  902. n.identifier = getStringFromBundle (env, "identifier", bundle);
  903. n.title = getStringFromBundle (env, "title", bundle);
  904. n.body = getStringFromBundle (env, "body", bundle);
  905. n.subtitle = getStringFromBundle (env, "subtitle", bundle);
  906. n.badgeNumber = getIntFromBundle (env, "badgeNumber", bundle);
  907. n.soundToPlay = URL (getStringFromBundle (env, "soundToPlay", bundle));
  908. n.properties = getPropertiesVarFromBundle (env, "properties", bundle);
  909. n.tickerText = getStringFromBundle (env, "tickerText", bundle);
  910. n.icon = getStringFromBundle (env, "icon", bundle);
  911. n.channelId = getStringFromBundle (env, "channelId", bundle);
  912. PushNotifications::Notification::Progress progress;
  913. progress.max = getIntFromBundle (env, "progressMax", bundle);
  914. progress.current = getIntFromBundle (env, "progressCurrent", bundle);
  915. progress.indeterminate = getBoolFromBundle (env, "progressIndeterminate", bundle);
  916. n.progress = progress;
  917. n.person = getStringFromBundle (env, "person", bundle);
  918. n.type = (PushNotifications::Notification::Type) getIntFromBundle (env, "type", bundle);
  919. n.priority = (PushNotifications::Notification::Priority) getIntFromBundle (env, "priority", bundle);
  920. n.lockScreenAppearance = (PushNotifications::Notification::LockScreenAppearance) getIntFromBundle (env, "lockScreenAppearance", bundle);
  921. n.groupId = getStringFromBundle (env, "groupId", bundle);
  922. n.groupSortKey = getStringFromBundle (env, "groupSortKey", bundle);
  923. n.groupSummary = getBoolFromBundle (env, "groupSummary", bundle);
  924. n.accentColour = Colour ((uint32) getIntFromBundle (env, "accentColour", bundle));
  925. n.ledColour = Colour ((uint32) getIntFromBundle (env, "ledColour", bundle));
  926. PushNotifications::Notification::LedBlinkPattern ledBlinkPattern;
  927. ledBlinkPattern.msToBeOn = getIntFromBundle (env, "ledBlinkPatternMsToBeOn", bundle);
  928. ledBlinkPattern.msToBeOff = getIntFromBundle (env, "ledBlinkPatternMsToBeOff", bundle);
  929. n.ledBlinkPattern = ledBlinkPattern;
  930. n.vibrationPattern = getLongArrayFromBundle (env, "vibrationPattern", bundle);
  931. n.shouldAutoCancel = getBoolFromBundle (env, "shouldAutoCancel", bundle);
  932. n.localOnly = getBoolFromBundle (env, "localOnly", bundle);
  933. n.ongoing = getBoolFromBundle (env, "ongoing", bundle);
  934. n.alertOnlyOnce = getBoolFromBundle (env, "alertOnlyOnce", bundle);
  935. n.timestampVisibility = (PushNotifications::Notification::TimestampVisibility) getIntFromBundle (env, "timestampVisibility", bundle);
  936. n.badgeIconType = (PushNotifications::Notification::BadgeIconType) getIntFromBundle (env, "badgeIconType", bundle);
  937. n.groupAlertBehaviour = (PushNotifications::Notification::GroupAlertBehaviour) getIntFromBundle (env, "groupAlertBehaviour", bundle);
  938. n.timeoutAfterMs = getLongFromBundle (env, "timeoutAfterMs", bundle);
  939. }
  940. return n;
  941. }
  942. static String getStringFromBundle (JNIEnv* env, const String& key, const LocalRef<jobject>& bundle)
  943. {
  944. auto keyString = javaString (key);
  945. if (env->CallBooleanMethod (bundle, JavaBundle.containsKey, keyString.get()))
  946. {
  947. auto value = LocalRef<jstring> ((jstring)env->CallObjectMethod (bundle, JavaBundle.getString, keyString.get()));
  948. return juceString (value);
  949. }
  950. return {};
  951. }
  952. static int getIntFromBundle (JNIEnv* env, const String& key, const LocalRef<jobject>& bundle)
  953. {
  954. auto keyString = javaString (key);
  955. if (env->CallBooleanMethod (bundle, JavaBundle.containsKey, keyString.get()))
  956. return env->CallIntMethod (bundle, JavaBundle.getInt, keyString.get());
  957. return 0;
  958. }
  959. // Converting to int on purpose!
  960. static int getLongFromBundle (JNIEnv* env, const String& key, const LocalRef<jobject>& bundle)
  961. {
  962. auto keyString = javaString (key);
  963. if (env->CallBooleanMethod (bundle, JavaBundle.containsKey, keyString.get()))
  964. return (int) env->CallLongMethod (bundle, JavaBundle.getLong, keyString.get());
  965. return 0;
  966. }
  967. static var getPropertiesVarFromBundle (JNIEnv* env, const String& key, const LocalRef<jobject>& bundle)
  968. {
  969. auto keyString = javaString (key);
  970. if (env->CallBooleanMethod (bundle, JavaBundle.containsKey, keyString.get()))
  971. {
  972. auto value = LocalRef<jobject> (env->CallObjectMethod (bundle, JavaBundle.getBundle, keyString.get()));
  973. return bundleWithPropertiesStringToVar (value);
  974. }
  975. return {};
  976. }
  977. static bool getBoolFromBundle (JNIEnv* env, const String& key, const LocalRef<jobject>& bundle)
  978. {
  979. auto keyString = javaString (key);
  980. if (env->CallBooleanMethod (bundle, JavaBundle.containsKey, keyString.get()))
  981. return env->CallBooleanMethod (bundle, JavaBundle.getBoolean, keyString.get());
  982. return false;
  983. }
  984. static Array<int> getLongArrayFromBundle (JNIEnv* env, const String& key, const LocalRef<jobject>& bundle)
  985. {
  986. auto keyString = javaString (key);
  987. if (env->CallBooleanMethod (bundle, JavaBundle.containsKey, keyString.get()))
  988. {
  989. auto array = LocalRef<jlongArray> ((jlongArray) env->CallObjectMethod (bundle, JavaBundle.getLongArray, keyString.get()));
  990. const int size = env->GetArrayLength (array.get());
  991. jlong* elements = env->GetLongArrayElements (array.get(), 0);
  992. Array<int> resultArray;
  993. for (int i = 0; i < size; ++i)
  994. resultArray.add ((int) *elements++);
  995. return resultArray;
  996. }
  997. return {};
  998. }
  999. static PushNotifications::Notification javaNotificationToJuceNotification (const LocalRef<jobject>& notification)
  1000. {
  1001. #if __ANDROID_API__ >= 20
  1002. auto* env = getEnv();
  1003. auto extras = LocalRef<jobject> (env->GetObjectField (notification, AndroidNotification.extras));
  1004. auto notificationData = LocalRef<jobject> (env->CallObjectMethod (extras, JavaBundle.getBundle,
  1005. javaString ("notificationData").get()));
  1006. if (notificationData.get() != nullptr)
  1007. return localNotificationBundleToJuceNotification (notificationData);
  1008. else
  1009. return remoteNotificationBundleToJuceNotification (extras);
  1010. #else
  1011. ignoreUnused (notification);
  1012. return {};
  1013. #endif
  1014. }
  1015. static PushNotifications::Notification remoteNotificationBundleToJuceNotification (const LocalRef<jobject>& bundle)
  1016. {
  1017. // This will probably work only for remote notifications that get delivered to system tray
  1018. PushNotifications::Notification n;
  1019. n.properties = bundleToVar (bundle);
  1020. return n;
  1021. }
  1022. static var bundleToVar (const LocalRef<jobject>& bundle)
  1023. {
  1024. if (bundle.get() != 0)
  1025. {
  1026. auto* env = getEnv();
  1027. auto keySet = LocalRef<jobject> (env->CallObjectMethod (bundle, JavaBundle.keySet));
  1028. auto iterator = LocalRef<jobject> (env->CallObjectMethod (keySet, JavaSet.iterator));
  1029. DynamicObject::Ptr dynamicObject = new DynamicObject();
  1030. for (;;)
  1031. {
  1032. if (! env->CallBooleanMethod (iterator, JavaIterator.hasNext))
  1033. break;
  1034. auto key = LocalRef<jstring> ((jstring) env->CallObjectMethod (iterator, JavaIterator.next));
  1035. auto object = LocalRef<jobject> (env->CallObjectMethod (bundle, JavaBundle.get, key.get()));
  1036. if (object.get() != nullptr)
  1037. {
  1038. auto objectAsString = LocalRef<jstring> ((jstring) env->CallObjectMethod (object, JavaObject.toString));
  1039. auto objectClass = LocalRef<jobject> (env->CallObjectMethod (object, JavaObject.getClass));
  1040. auto classAsString = LocalRef<jstring> ((jstring) env->CallObjectMethod (objectClass, JavaClass.getName));
  1041. // Note: seems that Firebase delivers values as strings always, so this check is rather unnecessary,
  1042. // at least till they change the behaviour.
  1043. var value = juceString (classAsString) == "java.lang.Bundle" ? bundleToVar (object) : var (juceString (objectAsString.get()));
  1044. dynamicObject->setProperty (juceString (key.get()), value);
  1045. }
  1046. else
  1047. {
  1048. dynamicObject->setProperty (juceString (key.get()), {});
  1049. }
  1050. }
  1051. return var (dynamicObject);
  1052. }
  1053. return {};
  1054. }
  1055. #if defined(JUCE_FIREBASE_MESSAGING_SERVICE_CLASSNAME)
  1056. static PushNotifications::Notification firebaseRemoteNotificationToJuceNotification (jobject remoteNotification)
  1057. {
  1058. auto* env = getEnv();
  1059. auto collapseKey = LocalRef<jstring> ((jstring) env->CallObjectMethod (remoteNotification, RemoteMessage.getCollapseKey));
  1060. auto from = LocalRef<jstring> ((jstring) env->CallObjectMethod (remoteNotification, RemoteMessage.getFrom));
  1061. auto messageId = LocalRef<jstring> ((jstring) env->CallObjectMethod (remoteNotification, RemoteMessage.getMessageId));
  1062. auto messageType = LocalRef<jstring> ((jstring) env->CallObjectMethod (remoteNotification, RemoteMessage.getMessageType));
  1063. auto to = LocalRef<jstring> ((jstring) env->CallObjectMethod (remoteNotification, RemoteMessage.getTo));
  1064. auto notification = LocalRef<jobject> (env->CallObjectMethod (remoteNotification, RemoteMessage.getNotification));
  1065. auto data = LocalRef<jobject> (env->CallObjectMethod (remoteNotification, RemoteMessage.getData));
  1066. const int64 sentTime = env->CallLongMethod (remoteNotification, RemoteMessage.getSentTime);
  1067. const int ttl = env->CallIntMethod (remoteNotification, RemoteMessage.getTtl);
  1068. auto keySet = LocalRef<jobject> (env->CallObjectMethod (data, JavaMap.keySet));
  1069. auto iterator = LocalRef<jobject> (env->CallObjectMethod (keySet, JavaSet.iterator));
  1070. DynamicObject::Ptr dataDynamicObject = new DynamicObject();
  1071. for (;;)
  1072. {
  1073. if (! env->CallBooleanMethod (iterator, JavaIterator.hasNext))
  1074. break;
  1075. auto key = LocalRef<jstring> ((jstring) env->CallObjectMethod (iterator, JavaIterator.next));
  1076. auto value = LocalRef<jstring> ((jstring) env->CallObjectMethod (data, JavaMap.get, key.get()));
  1077. dataDynamicObject->setProperty (juceString (key.get()), juceString (value.get()));
  1078. }
  1079. var dataVar (dataDynamicObject);
  1080. DynamicObject::Ptr propertiesDynamicObject = new DynamicObject();
  1081. propertiesDynamicObject->setProperty ("collapseKey", juceString (collapseKey.get()));
  1082. propertiesDynamicObject->setProperty ("from", juceString (from.get()));
  1083. propertiesDynamicObject->setProperty ("messageId", juceString (messageId.get()));
  1084. propertiesDynamicObject->setProperty ("messageType", juceString (messageType.get()));
  1085. propertiesDynamicObject->setProperty ("to", juceString (to.get()));
  1086. propertiesDynamicObject->setProperty ("sentTime", sentTime);
  1087. propertiesDynamicObject->setProperty ("ttl", ttl);
  1088. propertiesDynamicObject->setProperty ("data", dataVar);
  1089. PushNotifications::Notification n;
  1090. if (notification != 0)
  1091. {
  1092. auto body = LocalRef<jstring> ((jstring) env->CallObjectMethod (notification, RemoteMessageNotification.getBody));
  1093. auto bodyLocalizationKey = LocalRef<jstring> ((jstring) env->CallObjectMethod (notification, RemoteMessageNotification.getBodyLocalizationKey));
  1094. auto clickAction = LocalRef<jstring> ((jstring) env->CallObjectMethod (notification, RemoteMessageNotification.getClickAction));
  1095. auto color = LocalRef<jstring> ((jstring) env->CallObjectMethod (notification, RemoteMessageNotification.getColor));
  1096. auto icon = LocalRef<jstring> ((jstring) env->CallObjectMethod (notification, RemoteMessageNotification.getIcon));
  1097. auto sound = LocalRef<jstring> ((jstring) env->CallObjectMethod (notification, RemoteMessageNotification.getSound));
  1098. auto tag = LocalRef<jstring> ((jstring) env->CallObjectMethod (notification, RemoteMessageNotification.getTag));
  1099. auto title = LocalRef<jstring> ((jstring) env->CallObjectMethod (notification, RemoteMessageNotification.getTitle));
  1100. auto titleLocalizationKey = LocalRef<jstring> ((jstring) env->CallObjectMethod (notification, RemoteMessageNotification.getTitleLocalizationKey));
  1101. auto link = LocalRef<jobject> (env->CallObjectMethod (notification, RemoteMessageNotification.getLink));
  1102. auto bodyLocalizationArgs = LocalRef<jobjectArray> ((jobjectArray) env->CallObjectMethod (notification, RemoteMessageNotification.getBodyLocalizationArgs));
  1103. auto titleLocalizationArgs = LocalRef<jobjectArray> ((jobjectArray) env->CallObjectMethod (notification, RemoteMessageNotification.getTitleLocalizationArgs));
  1104. n.identifier = juceString (tag.get());
  1105. n.title = juceString (title.get());
  1106. n.body = juceString (body.get());
  1107. n.soundToPlay = URL (juceString (sound.get()));
  1108. auto colourString = juceString (color.get()).substring (1);
  1109. const uint8 r = (uint8) colourString.substring (0, 2).getIntValue();
  1110. const uint8 g = (uint8) colourString.substring (2, 4).getIntValue();
  1111. const uint8 b = (uint8) colourString.substring (4, 6).getIntValue();
  1112. n.accentColour = Colour (r, g, b);
  1113. // Note: ignoring icon, because Firebase passes it as a string.
  1114. propertiesDynamicObject->setProperty ("clickAction", juceString (clickAction.get()));
  1115. propertiesDynamicObject->setProperty ("bodyLocalizationKey", juceString (bodyLocalizationKey.get()));
  1116. propertiesDynamicObject->setProperty ("titleLocalizationKey", juceString (titleLocalizationKey.get()));
  1117. propertiesDynamicObject->setProperty ("bodyLocalizationArgs", javaStringArrayToJuce (bodyLocalizationArgs));
  1118. propertiesDynamicObject->setProperty ("titleLocalizationArgs", javaStringArrayToJuce (titleLocalizationArgs));
  1119. propertiesDynamicObject->setProperty ("link", link.get() != 0 ? juceString ((jstring) env->CallObjectMethod (link, AndroidUri.toString)) : String());
  1120. }
  1121. n.properties = var (propertiesDynamicObject);
  1122. return n;
  1123. }
  1124. #endif
  1125. void setupChannels (const Array<ChannelGroup>& groups, const Array<Channel>& channels)
  1126. {
  1127. #if __ANDROID_API__ >= 26
  1128. auto* env = getEnv();
  1129. if (env->CallStaticIntMethod (JuceAppActivity, JuceAppActivity.getAndroidSDKVersion) < 26)
  1130. return;
  1131. auto notificationManager = getNotificationManager();
  1132. jassert (notificationManager.get() != 0);
  1133. if (notificationManager.get() == 0)
  1134. return;
  1135. for (const auto& g : groups)
  1136. {
  1137. // Channel group identifier and name have to be set.
  1138. jassert (g.identifier.isNotEmpty() && g.name.isNotEmpty());
  1139. if (g.identifier.isNotEmpty() && g.name.isNotEmpty())
  1140. {
  1141. auto group = LocalRef<jobject> (env->NewObject (NotificationChannelGroup, NotificationChannelGroup.constructor,
  1142. javaString (g.identifier).get(), javaString (g.name).get()));
  1143. env->CallVoidMethod (notificationManager, NotificationManagerApi26.createNotificationChannelGroup, group.get());
  1144. }
  1145. }
  1146. for (const auto& c : channels)
  1147. {
  1148. // Channel identifier, name and group have to be set.
  1149. jassert (c.identifier.isNotEmpty() && c.name.isNotEmpty() && c.groupId.isNotEmpty());
  1150. if (c.identifier.isEmpty() || c.name.isEmpty() || c.groupId.isEmpty())
  1151. continue;
  1152. auto channel = LocalRef<jobject> (env->NewObject (NotificationChannel, NotificationChannel.constructor,
  1153. javaString (c.identifier).get(), javaString (c.name).get(), c.importance));
  1154. env->CallVoidMethod (channel, NotificationChannel.enableLights, c.enableLights);
  1155. env->CallVoidMethod (channel, NotificationChannel.enableVibration, c.enableVibration);
  1156. env->CallVoidMethod (channel, NotificationChannel.setBypassDnd, c.bypassDoNotDisturb);
  1157. env->CallVoidMethod (channel, NotificationChannel.setDescription, javaString (c.description).get());
  1158. env->CallVoidMethod (channel, NotificationChannel.setGroup, javaString (c.groupId).get());
  1159. env->CallVoidMethod (channel, NotificationChannel.setImportance, c.importance);
  1160. env->CallVoidMethod (channel, NotificationChannel.setLightColor, c.ledColour.getARGB());
  1161. env->CallVoidMethod (channel, NotificationChannel.setLockscreenVisibility, c.lockScreenAppearance);
  1162. env->CallVoidMethod (channel, NotificationChannel.setShowBadge, c.canShowBadge);
  1163. const int size = c.vibrationPattern.size();
  1164. if (size > 0)
  1165. {
  1166. auto array = LocalRef<jlongArray> (env->NewLongArray (size));
  1167. jlong* elements = env->GetLongArrayElements (array, 0);
  1168. for (int i = 0; i < size; ++i)
  1169. elements[i] = (jlong) c.vibrationPattern[i];
  1170. env->SetLongArrayRegion (array, 0, size, elements);
  1171. env->CallVoidMethod (channel, NotificationChannel.setVibrationPattern, array.get());
  1172. env->CallVoidMethod (channel, NotificationChannel.enableVibration, c.enableVibration);
  1173. }
  1174. auto audioAttributesBuilder = LocalRef<jobject> (env->NewObject (AudioAttributesBuilder, AudioAttributesBuilder.constructor));
  1175. const int contentTypeSonification = 4;
  1176. const int usageNotification = 5;
  1177. env->CallObjectMethod (audioAttributesBuilder, AudioAttributesBuilder.setContentType, contentTypeSonification);
  1178. env->CallObjectMethod (audioAttributesBuilder, AudioAttributesBuilder.setUsage, usageNotification);
  1179. auto audioAttributes = LocalRef<jobject> (env->CallObjectMethod (audioAttributesBuilder, AudioAttributesBuilder.build));
  1180. env->CallVoidMethod (channel, NotificationChannel.setSound, juceUrlToAndroidUri (c.soundToPlay).get(), audioAttributes.get());
  1181. env->CallVoidMethod (notificationManager, NotificationManagerApi26.createNotificationChannel, channel.get());
  1182. }
  1183. #else
  1184. ignoreUnused (groups, channels);
  1185. #endif
  1186. }
  1187. void getPendingLocalNotifications() const {}
  1188. void removePendingLocalNotification (const String&) {}
  1189. void removeAllPendingLocalNotifications() {}
  1190. static bool intentActionContainsAnyOf (jobject intent, const StringArray& strings, bool includePackageName)
  1191. {
  1192. auto* env = getEnv();
  1193. String packageName = includePackageName ? juceString ((jstring) env->CallObjectMethod (android.activity,
  1194. JuceAppActivity.getPackageName))
  1195. : String{};
  1196. String intentAction = juceString ((jstring) env->CallObjectMethod (intent, AndroidIntent.getAction));
  1197. for (const auto& string : strings)
  1198. if (intentAction.contains (packageName + string))
  1199. return true;
  1200. return false;
  1201. }
  1202. static bool isDeleteNotificationIntent (jobject intent)
  1203. {
  1204. return intentActionContainsAnyOf (intent, StringArray (".JUCE_NOTIFICATION_DELETED"), true);
  1205. }
  1206. static bool isLocalNotificationIntent (jobject intent)
  1207. {
  1208. return intentActionContainsAnyOf (intent, { ".JUCE_NOTIFICATION.",
  1209. ".JUCE_NOTIFICATION_BUTTON_ACTION.",
  1210. ".JUCE_NOTIFICATION_TEXT_INPUT_ACTION." },
  1211. true);
  1212. }
  1213. static bool isRemoteNotificationIntent (jobject intent)
  1214. {
  1215. auto* env = getEnv();
  1216. auto categories = LocalRef<jobject> (env->CallObjectMethod (intent, AndroidIntent.getCategories));
  1217. int categoriesNum = categories != 0
  1218. ? env->CallIntMethod (categories, JavaSet.size)
  1219. : 0;
  1220. if (categoriesNum == 0)
  1221. return false;
  1222. if (! env->CallBooleanMethod (categories, JavaSet.contains, javaString ("android.intent.category.LAUNCHER").get()))
  1223. return false;
  1224. if (! intentActionContainsAnyOf (intent, StringArray ("android.intent.action.MAIN"), false))
  1225. return false;
  1226. auto extras = LocalRef<jobject> (env->CallObjectMethod (intent, AndroidIntent.getExtras));
  1227. if (extras == 0)
  1228. return false;
  1229. return env->CallBooleanMethod (extras, JavaBundle.containsKey, javaString ("google.sent_time").get())
  1230. && env->CallBooleanMethod (extras, JavaBundle.containsKey, javaString ("google.message_id").get());
  1231. }
  1232. PushNotifications& owner;
  1233. };
  1234. bool juce_handleNotificationIntent (void* intent)
  1235. {
  1236. auto* instance = PushNotifications::getInstanceWithoutCreating();
  1237. if (PushNotifications::Pimpl::isDeleteNotificationIntent ((jobject) intent))
  1238. {
  1239. if (instance)
  1240. instance->pimpl->notifyListenersAboutLocalNotificationDeleted (LocalRef<jobject> ((jobject) intent));
  1241. return true;
  1242. }
  1243. else if (PushNotifications::Pimpl::isLocalNotificationIntent ((jobject) intent))
  1244. {
  1245. if (instance)
  1246. instance->pimpl->notifyListenersAboutLocalNotification (LocalRef<jobject> ((jobject) intent));
  1247. return true;
  1248. }
  1249. #if defined(JUCE_FIREBASE_MESSAGING_SERVICE_CLASSNAME)
  1250. else if (PushNotifications::Pimpl::isRemoteNotificationIntent ((jobject) intent))
  1251. {
  1252. if (instance)
  1253. instance->pimpl->notifyListenersAboutRemoteNotificationFromSystemTray (LocalRef<jobject> ((jobject) intent));
  1254. return true;
  1255. }
  1256. #endif
  1257. return false;
  1258. }
  1259. void juce_firebaseDeviceNotificationsTokenRefreshed (void* token)
  1260. {
  1261. if (auto* instance = PushNotifications::getInstanceWithoutCreating())
  1262. instance->pimpl->notifyListenersTokenRefreshed (juceString (static_cast<jstring> (token)));
  1263. }
  1264. void juce_firebaseRemoteNotificationReceived (void* remoteMessage)
  1265. {
  1266. if (auto* instance = PushNotifications::getInstanceWithoutCreating())
  1267. instance->pimpl->notifyListenersAboutRemoteNotificationFromService (LocalRef<jobject> (static_cast<jobject> (remoteMessage)));
  1268. }
  1269. void juce_firebaseRemoteMessagesDeleted()
  1270. {
  1271. if (auto* instance = PushNotifications::getInstanceWithoutCreating())
  1272. instance->pimpl->notifyListenersAboutRemoteNotificationsDeleted();
  1273. }
  1274. void juce_firebaseRemoteMessageSent (void* messageId)
  1275. {
  1276. if (auto* instance = PushNotifications::getInstanceWithoutCreating())
  1277. instance->pimpl->notifyListenersAboutUpstreamMessageSent (LocalRef<jstring> (static_cast<jstring> (messageId)));
  1278. }
  1279. void juce_firebaseRemoteMessageSendError (void* messageId, void* error)
  1280. {
  1281. if (auto* instance = PushNotifications::getInstanceWithoutCreating())
  1282. instance->pimpl->notifyListenersAboutUpstreamMessageSendingError (LocalRef<jstring> (static_cast<jstring> (messageId)),
  1283. LocalRef<jstring> (static_cast<jstring> (error)));
  1284. }
  1285. } // namespace juce