diff --git a/android/src/main/java/com/evollu/react/fcm/MessagingService.java b/android/src/main/java/com/evollu/react/fcm/MessagingService.java index c85deff110c9392a5e17a0d4d2e4763539c7608b..fe48fcfcb229747b4cbf0beb6450bc30c67cddec 100644 --- a/android/src/main/java/com/evollu/react/fcm/MessagingService.java +++ b/android/src/main/java/com/evollu/react/fcm/MessagingService.java @@ -22,7 +22,33 @@ public class MessagingService extends FirebaseMessagingService { i.putExtra("data", remoteMessage); handleBadge(remoteMessage); buildLocalNotification(remoteMessage); - sendOrderedBroadcast(i, null); + + // We need to run this on the main thread, as the React code assumes that is true. + // Namely, DevServerHelper constructs a Handler() without a Looper, which triggers: + // "Can't create handler inside thread that has not called Looper.prepare()" + Handler handler = new Handler(Looper.getMainLooper()); + handler.post(new Runnable() { + public void run() { + // Construct and load our normal React JS code bundle + ReactInstanceManager mReactInstanceManager = ((ReactApplication) getApplication()).getReactNativeHost().getReactInstanceManager(); + ReactContext context = mReactInstanceManager.getCurrentReactContext(); + // If it's constructed, send a notification + if (context != null) { + context.sendOrderedBroadcast(message, null); + } else { + // Otherwise wait for construction, then send the notification + mReactInstanceManager.addReactInstanceEventListener(new ReactInstanceManager.ReactInstanceEventListener() { + public void onReactContextInitialized(ReactContext context) { + context.sendOrderedBroadcast(message, null); + } + }); + if (!mReactInstanceManager.hasStartedCreatingInitialContext()) { + // Construct it in the background + mReactInstanceManager.createReactContextInBackground(); + } + } + } + }); } public void handleBadge(RemoteMessage remoteMessage) { @@ -61,4 +87,4 @@ public class MessagingService extends FirebaseMessagingService { } } -} \ No newline at end of file +}