Skip to content
This repository has been archived by the owner on Sep 14, 2024. It is now read-only.

Commit

Permalink
fix: add background and foreground support
Browse files Browse the repository at this point in the history
  • Loading branch information
gtokman committed Apr 19, 2024
1 parent e8b9256 commit 89b6e30
Show file tree
Hide file tree
Showing 6 changed files with 49 additions and 21 deletions.
10 changes: 8 additions & 2 deletions android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,14 @@ dependencies {
//noinspection GradleDynamicVersion
implementation "com.facebook.react:react-native:+"
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation(platform("com.google.firebase:firebase-bom:32.7.2"))
implementation(platform("com.google.firebase:firebase-bom:32.8.1"))
implementation "com.google.firebase:firebase-messaging"
implementation 'androidx.core:core-ktx:1.12.0'
implementation 'androidx.core:core-ktx:1.13.0'
implementation 'androidx.lifecycle:lifecycle-process:2.7.0'
}
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
kotlinOptions {
languageVersion = "1.9"
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,6 @@ class FirebaseMessagingService : FirebaseMessagingService() {
}
} catch (exception: Exception) {
Log.e(TAG, "Something went wrong while starting headless task: ${exception.message}")
PushNotificationEventManager.sendEvent(
PushNotificationEventType.BACKGROUND_MESSAGE_RECEIVED, payload.toWritableMap()
)
}
}
}
Expand Down
32 changes: 28 additions & 4 deletions android/src/main/java/com/candlefinance/push/NotificationUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.ProcessLifecycleOwner
import com.facebook.react.HeadlessJsTaskService
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.WritableMap
Expand All @@ -38,6 +39,7 @@ class PushNotificationsConstants {
const val URL = "url" // url
const val DEEPLINK = "deeplink" // deeplink
const val TITLE = "title" // title
const val BODY = "body" // body
const val IMAGEURL = "imageUrl" // imageUrl
const val DEFAULT_NOTIFICATION_CHANNEL_ID = "default_notification_channel_id" // default_notification_channel_id
}
Expand Down Expand Up @@ -106,6 +108,7 @@ class PushNotificationsUtils(
notificationBuilder
.setSmallIcon(getResourceIdByName("ic_default_notification", "drawable"))
.setContentTitle(notificationContent[PushNotificationsConstants.TITLE])
.setContentText(notificationContent[PushNotificationsConstants.BODY])
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)

Expand All @@ -114,9 +117,17 @@ class PushNotificationsUtils(
Log.d("PushNotificationsUtils", "targetClass is not null")
val intent = Intent(context, targetClass).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
val url = notificationContent[PushNotificationsConstants.URL]
val deepLink = notificationContent[PushNotificationsConstants.DEEPLINK]

if (url != null) {
putExtra(PushNotificationsConstants.URL, url)
}

if (deepLink != null) {
putExtra(PushNotificationsConstants.DEEPLINK, deepLink)
}
putExtra(PushNotificationsConstants.OPENAPP, true)
putExtra(PushNotificationsConstants.URL, notificationContent[PushNotificationsConstants.URL])
putExtra(PushNotificationsConstants.DEEPLINK, notificationContent[PushNotificationsConstants.DEEPLINK])
}

notificationBuilder.setContentIntent(
Expand Down Expand Up @@ -168,7 +179,18 @@ class PushNotificationUtils(context: Context) {
Log.d("PushNotificationUtils", "Show notification with payload: $payload")

val notificationId = (System.currentTimeMillis() % Int.MAX_VALUE).toInt()
utils.showNotification(notificationId, payload, payload.targetClass)
val targetClass = payload.rawData["targetClass"]?.let {
Log.d("PushNotificationUtils", "targetClass: $it")
try {
Class.forName(it)
} catch (e: ClassNotFoundException) {
Log.e("PushNotificationUtils", "Class not found: $it")
null
}
}
if (targetClass != null) {
utils.showNotification(notificationId, payload, targetClass)
}
}

fun isAppInForeground(): Boolean {
Expand Down Expand Up @@ -205,6 +227,8 @@ open class NotificationPayload(

fun toWritableMap(): WritableMap {
val map = Arguments.createMap()
map.putMap("rawData", Arguments.makeNativeMap(rawData))
map.putString("channelId", channelId)
rawData.forEach { (key, value) -> map.putString(key, value) }
return map
}
Expand Down Expand Up @@ -265,4 +289,4 @@ class AppLifecycleListener : DefaultLifecycleObserver {
isAppInBackground = true
isAppInForeground = false
}
}
}
12 changes: 7 additions & 5 deletions android/src/main/java/com/candlefinance/push/PushModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -158,8 +158,7 @@ class PushModule(
}

override fun getConstants(): MutableMap<String, Any> = hashMapOf(
"NativeEvent" to PushNotificationEventType.entries
.associateBy({ it.name }, { it.value }),
"NativeEvent" to PushNotificationEventType.values().associateBy({ it.name }, { it.value }),
"NativeHeadlessTaskKey" to PushNotificationHeadlessTaskService.HEADLESS_TASK_KEY
)

Expand All @@ -171,6 +170,7 @@ class PushModule(
* Send notification opened app event to JS layer if the app is in a background state
*/
override fun onNewIntent(intent: Intent) {
Log.d(TAG, "New intent received")
val payload = NotificationPayload.fromIntent(intent)
if (payload != null) {
PushNotificationEventManager.sendEvent(
Expand All @@ -184,6 +184,7 @@ class PushModule(
* store the app launching notification if app is in a quit state
*/
override fun onHostResume() {
Log.d(TAG, "App resumed")
if (isAppLaunch) {
isAppLaunch = false
PushNotificationEventManager.init(reactApplicationContext)
Expand Down Expand Up @@ -215,6 +216,7 @@ class PushModule(
}
} else {
// Wipe the launching notification as app was re-opened by some other means
Log.d(TAG, "Wipe launching notification")
launchNotification = null
}
}
Expand Down Expand Up @@ -271,9 +273,9 @@ class PushNotificationPermission(private val context: Context) {
// Request the permission
Log.d(TAG, "Requesting notification permission on Android 12 or higher")
ActivityCompat.requestPermissions(
context,
arrayOf(Manifest.permission.POST_NOTIFICATIONS),
requestId.hashCode()
context,
arrayOf(Manifest.permission.POST_NOTIFICATIONS),
Math.abs(requestId.hashCode())
)
Log.d(TAG, "Requesting notification permission on Android 12 or higher")
}
Expand Down
12 changes: 5 additions & 7 deletions example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,11 @@ export default function App() {
}
);
return () => {
if (Platform.OS === 'ios') {
Push.removeListeners(NativeEvent.TOKEN_RECEIVED);
Push.removeListeners(NativeEvent.BACKGROUND_MESSAGE_RECEIVED);
Push.removeListeners(NativeEvent.NOTIFICATION_OPENED);
Push.removeListeners(NativeEvent.FOREGROUND_MESSAGE_RECEIVED);
Push.removeListeners(NativeEvent.LAUNCH_NOTIFICATION_OPENED);
}
Push.removeListeners(NativeEvent.TOKEN_RECEIVED);
Push.removeListeners(NativeEvent.BACKGROUND_MESSAGE_RECEIVED);
Push.removeListeners(NativeEvent.NOTIFICATION_OPENED);
Push.removeListeners(NativeEvent.FOREGROUND_MESSAGE_RECEIVED);
Push.removeListeners(NativeEvent.LAUNCH_NOTIFICATION_OPENED);
};
}, [isGranted]);

Expand Down
1 change: 1 addition & 0 deletions src/apis/addMessageEventListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export const addMessageEventListener = (
) => void
): EmitterSubscription =>
nativeEventEmitter.addListener(event, (nativeMessage: NativeMessage) => {
console.log('nativeMessage', nativeMessage);
listener(
normalizeNativeMessage(nativeMessage),
nativeMessage.completionHandlerId
Expand Down

0 comments on commit 89b6e30

Please sign in to comment.