Audio plugin host https://kx.studio/carla
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.

1649 lines
86KB

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