Skip to content

Commit ba298b6

Browse files
committed
fix: prevent crash when cleaning up uninitialized SDK on destroy
* Wrap removeHandlers() and removeObservers() calls in try-catch blocks within onHostDestroy() and onCatalystInstanceDestroy() to handle cases where the native OneSignal SDK throws "Must call 'initWithContext' before use" during activity destruction. * Also move the oneSignalInitDone flag further down past the native `OneSignal.initWithContext(context, appId)` call.
1 parent 1429d6e commit ba298b6

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

android/src/main/java/com/onesignal/rnonesignalandroid/RNOneSignal.java

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,11 @@ public void onClick(INotificationClickEvent event) {
172172
};
173173

174174
private void removeObservers() {
175+
if(!oneSignalInitDone) {
176+
Logging.debug("OneSignal React-Native SDK not initialized yet. Could not remove observers.", null);
177+
return;
178+
}
179+
175180
this.removePermissionObserver();
176181
this.removePushSubscriptionObserver();
177182
this.removeUserStateObserver();
@@ -226,8 +231,12 @@ public String getName() {
226231

227232
@Override
228233
public void onHostDestroy() {
229-
removeHandlers();
230-
removeObservers();
234+
try {
235+
removeHandlers();
236+
removeObservers();
237+
} catch (Exception e) {
238+
Logging.debug("OneSignal SDK not fully initialized. Could not remove handlers/observers: " + e.getMessage(), null);
239+
}
231240
}
232241

233242
@Override
@@ -238,8 +247,12 @@ public void onHostResume() {}
238247

239248
@Override
240249
public void onCatalystInstanceDestroy() {
241-
removeHandlers();
242-
removeObservers();
250+
try {
251+
removeHandlers();
252+
removeObservers();
253+
} catch (Exception e) {
254+
Logging.debug("OneSignal SDK not fully initialized. Could not remove handlers/observers: " + e.getMessage(), null);
255+
}
243256
}
244257

245258
// OneSignal namespace methods
@@ -254,15 +267,14 @@ public void initialize(String appId) {
254267
return;
255268
}
256269

257-
oneSignalInitDone = true;
258-
259270
if (context == null) {
260271
// in some cases, especially when react-native-navigation is installed,
261272
// the activity can be null, so we can initialize with the context instead
262273
context = mReactApplicationContext.getApplicationContext();
263274
}
264275

265276
OneSignal.initWithContext(context, appId);
277+
oneSignalInitDone = true;
266278
}
267279

268280
@ReactMethod

0 commit comments

Comments
 (0)