Skip to content

Commit 2e46ce6

Browse files
authored
fix(Android): app shows notifications in foreground state (#7012)
1 parent 48c5fc2 commit 2e46ce6

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

android/app/build.gradle

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,9 @@ dependencies {
152152

153153
// For SecureKeystore (EncryptedSharedPreferences)
154154
implementation 'androidx.security:security-crypto:1.1.0'
155+
156+
// For ProcessLifecycleOwner (app foreground detection)
157+
implementation 'androidx.lifecycle:lifecycle-process:2.8.7'
155158
}
156159

157160
apply plugin: 'com.google.gms.google-services'

android/app/src/main/java/chat/rocket/reactnative/notification/CustomPushNotification.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
import android.util.Log;
1818

1919
import androidx.annotation.Nullable;
20+
import androidx.lifecycle.Lifecycle;
21+
import androidx.lifecycle.ProcessLifecycleOwner;
2022

2123
import com.google.gson.Gson;
2224

@@ -68,6 +70,14 @@ public CustomPushNotification(Context context, Bundle bundle) {
6870
public static void clearMessages(int notId) {
6971
notificationMessages.remove(Integer.toString(notId));
7072
}
73+
74+
/**
75+
* Checks if the app is currently in the foreground.
76+
* Uses ProcessLifecycleOwner to reliably detect app state.
77+
*/
78+
public static boolean isAppInForeground() {
79+
return ProcessLifecycleOwner.get().getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED);
80+
}
7181

7282
public void onReceived() {
7383
String notId = mBundle.getString("notId");
@@ -228,6 +238,15 @@ private void showNotification(Bundle bundle, Ejson ejson, String notId) {
228238
if (ENABLE_VERBOSE_LOGS) {
229239
Log.d(TAG, "[Before add to notificationMessages] notId=" + notId + ", bundle.message length=" + (bundle.getString("message") != null ? bundle.getString("message").length() : 0) + ", bundle.notificationLoaded=" + bundle.getBoolean("notificationLoaded", false));
230240
}
241+
242+
// Don't show notification if app is in foreground
243+
if (isAppInForeground()) {
244+
if (ENABLE_VERBOSE_LOGS) {
245+
Log.d(TAG, "App is in foreground, skipping native notification");
246+
}
247+
return;
248+
}
249+
231250
notificationMessages.get(notId).add(bundle);
232251
if (ENABLE_VERBOSE_LOGS) {
233252
Log.d(TAG, "[After add] notificationMessages[" + notId + "].size=" + notificationMessages.get(notId).size());

0 commit comments

Comments
 (0)