diff --git a/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java b/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java index 1df1978dc49..341d886bfed 100644 --- a/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java +++ b/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java @@ -11081,12 +11081,39 @@ protected final void sendRegisteredForPush(String id) { } } - protected final void pushReceived(String data) { - if (callback != null) { + /// One push handed to `PushDispatcher` by `#pushReceived(String)`. + private static final class PushDelivery implements Runnable { + private final PushCallback callback; + private final String data; + + PushDelivery(PushCallback callback, String data) { + this.callback = callback; + this.data = data; + } + + @Override + public void run() { callback.push(data); } } + protected final void pushReceived(final String data) { + if (callback != null) { + // Through PushDispatcher like every port path, so a push is held while a + // blocking call is in progress. Inside a delivery (a port path that ends here) + // it is the same push, so deliver it in place -- on the EDT only, which is the one + // thread that delivers. A caller on another thread is marshalled to the EDT, so its + // delivery is asynchronous where master called the callback in place; no port + // calls this off the EDT today. + final PushCallback c = callback; + if (Display.getInstance().isEdt() && PushDispatcher.isDelivering()) { + c.push(data); + return; + } + PushDispatcher.dispatch(new PushDelivery(c, data)); + } + } + /// Sets the frequency for polling the server in case of polling based push notification /// /// #### Parameters diff --git a/CodenameOne/src/com/codename1/impl/PushDispatcher.java b/CodenameOne/src/com/codename1/impl/PushDispatcher.java new file mode 100644 index 00000000000..e9b879d3546 --- /dev/null +++ b/CodenameOne/src/com/codename1/impl/PushDispatcher.java @@ -0,0 +1,294 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.impl; + +import com.codename1.io.Log; +import com.codename1.push.PushContent; +import com.codename1.ui.Display; + +import java.util.ArrayList; +import java.util.Timer; + +/// Delivers incoming push messages to the application at a point where it is safe to act on them. +/// +/// A push can arrive while the application is still inside a blocking call on the EDT: a modal +/// `Dialog` shown from `start()`, an `invokeAndBlock()`, a `NetworkManager.addToQueueAndWait()`. +/// The EDT keeps serving events inside such a call, so a push delivered there runs in the middle +/// of the code that blocked -- typically before the login or main form exists. That is the +/// "crashes before login, works with a delay sometimes" race. +/// +/// The ports therefore hand every push to `#dispatch(java.lang.Runnable)` instead of calling the +/// callback themselves. While no blocking call is in progress the push runs at once, exactly as +/// before. While one is, the push is held and runs, in arrival order, as soon as the outermost +/// blocking call returns. No push is held longer than 15 seconds, so a dialog left open while +/// the application is in the background cannot make a push miss the completion deadline the OS +/// imposes on it. +/// +/// A held push keeps its own copy of `PushContent` (and the `pushType` property), taken when the +/// push reaches the EDT: the ports write those globals when a push arrives, so a second push +/// arriving during the hold would otherwise be what the first one reads when it is finally +/// delivered. Two pushes whose content is written before either reaches the EDT share the later +/// content, as they always have; the iOS replay path and the Android pending path write the +/// content inside the delivery and are exact. +/// +/// The deferral can be switched off with `com.codename1.push.Push#setDeliveryDeferred(boolean)`. +/// +/// Everything here is touched on the EDT only: `#dispatch(java.lang.Runnable)` marshals a call +/// from another thread onto it, and `Display` calls the blocking hooks from the EDT. +/// +/// This is an implementation class used by the ports; applications use `Push`. +public final class PushDispatcher { + private static final ArrayList HELD = new ArrayList(); + private static int blockingDepth; + /// The blocking depth at which the delivery now running started, or -1 when none is running. + private static int deliveryDepth = -1; + private static boolean deferred = true; + private static boolean drainScheduled; + + /// The longest a push is held, in milliseconds. Counted from when the push reaches the EDT + /// and enforced through the EDT, so it is not a hard bound on the time since the OS handed the + /// push over. It is kept well below the roughly 30 seconds iOS allows a background push before + /// completion must be reported, leaving room for the queueing on either side. + static final int MAX_HOLD_MS = 15000; + + /// The limit in force; `#MAX_HOLD_MS` except in tests, which cannot wait that long. + static int holdLimitMs = MAX_HOLD_MS; + + /// Identifies the current hold-limit timer. A timeout whose runnable was already queued when + /// the hold ended must not act on a later hold, so each timer carries the generation it was + /// armed with and does nothing unless it is still the current one. + private static int holdGeneration; + private static boolean holdArmed; + private static Timer holdTimer; + + private PushDispatcher() { + } + + /// Switches the deferral on (the default) or off. Off, a push is delivered as soon as it + /// reaches the EDT, even inside a blocking call. Pushes already held are then delivered too. + /// + /// #### Parameters + /// + /// - `defer`: true to hold pushes while a blocking call is in progress + public static void setDeferred(boolean defer) { + deferred = defer; + if (!defer && !HELD.isEmpty() && Display.isInitialized()) { + scheduleDrain(); + } + } + + /// #### Returns + /// + /// true if pushes are held while a blocking call is in progress + public static boolean isDeferred() { + return deferred; + } + + /// Runs `delivery` -- the port's whole delivery of one push, callback call included -- on the + /// EDT, now if that is safe and otherwise once the blocking call in progress returns. + /// + /// #### Parameters + /// + /// - `delivery`: the code that delivers the push to the application + public static void dispatch(final Runnable delivery) { + Display d = Display.getInstance(); + if (!d.isEdt()) { + d.callSerially(new Runnable() { + @Override + public void run() { + dispatch(delivery); + } + }); + return; + } + // While a delivery is running, a new push waits for it to finish, however it got here: + // through a blocking call in the handler, or through a serial call pumped by flushEdt() + // before a modal Dialog raises the blocking depth. (The generic pushReceived path, which + // a port delivery may end in, checks isDelivering() and calls the callback directly.) + if (!deferred || (deliveryDepth < 0 && blockingDepth == 0 && HELD.isEmpty())) { + run(delivery); + return; + } + HELD.add(withContent(delivery)); + armHoldLimit(d); + if (blockingDepth == 0) { + scheduleDrain(); + } + } + + /// Called by `Display` on the EDT when a blocking call starts. + public static void blockingStarted() { + blockingDepth++; + } + + /// Called by `Display` on the EDT when a blocking call returns, normally or not. + public static void blockingEnded() { + if (blockingDepth > 0) { + blockingDepth--; + } + if (blockingDepth == 0 && !HELD.isEmpty()) { + scheduleDrain(); + } + } + + private static void run(Runnable delivery) { + int saved = deliveryDepth; + deliveryDepth = blockingDepth; + try { + delivery.run(); + } finally { + deliveryDepth = saved; + if (deliveryDepth < 0 && blockingDepth == 0 && !HELD.isEmpty()) { + scheduleDrain(); + } + } + } + + /// #### Returns + /// + /// true while a push delivery is running on the EDT; a port path that ends in the generic + /// `pushReceived` uses it to deliver in place instead of queueing the same push again + public static boolean isDelivering() { + return deliveryDepth >= 0; + } + + /// Wraps `delivery` so it runs with the PushContent and pushType that were current when it + /// was held. Paths that set those inside the delivery simply overwrite the restored values. + private static Runnable withContent(final Runnable delivery) { + final PushContent content = PushContent.get(); + final String pushType = Display.getInstance().getProperty("pushType", null); + restore(content, pushType); + return new Runnable() { + @Override + public void run() { + restore(content, pushType); + delivery.run(); + } + }; + } + + /// Puts back what the snapshot had, so a held push looks the same to the application as one + /// delivered at once: no PushContent type written where there was none. + private static void restore(PushContent c, String pushType) { + // Null as well: getProperty reads a null value as absent, and a held push must not see + // the pushType a later push wrote during the hold. + Display.getInstance().setProperty("pushType", pushType); + PushContent.reset(); + if (c == null) { + return; + } + PushContent.setTitle(c.getTitle()); + PushContent.setBody(c.getBody()); + PushContent.setImageUrl(c.getImageUrl()); + PushContent.setCategory(c.getCategory()); + PushContent.setMetaData(c.getMetaData()); + PushContent.setActionId(c.getActionId()); + PushContent.setActionTitle(c.getActionTitle()); + PushContent.setTextResponse(c.getTextResponse()); + if (c.getType() != 0) { + PushContent.setType(c.getType()); + } + } + + private static void armHoldLimit(Display d) { + if (holdArmed) { + return; + } + holdArmed = true; + final int generation = ++holdGeneration; + holdTimer = d.setTimeout(holdLimitMs, new Runnable() { + @Override + public void run() { + if (!holdArmed || holdGeneration != generation) { + return; + } + endHoldLimit(); + deliverHeldNow(); + } + }); + } + + /// Stops the current hold-limit timer, which also ends its thread: `Display.setTimeout` gives + /// every timer a thread of its own, and one never cancelled keeps it. + private static void endHoldLimit() { + holdArmed = false; + Timer t = holdTimer; + holdTimer = null; + if (t != null) { + t.cancel(); + } + } + + private static void scheduleDrain() { + if (drainScheduled) { + return; + } + drainScheduled = true; + // A fresh EDT task rather than delivering from blockingEnded(): the code that blocked + // gets to finish (show its form, store its state) before the push sees the app. + Display.getInstance().callSerially(new Runnable() { + @Override + public void run() { + drainScheduled = false; + drain(false); + } + }); + } + + /// The hold limit expired with a blocking call still in progress: deliver what is held + /// regardless, as releases without the deferral would have. + private static void deliverHeldNow() { + if (HELD.isEmpty()) { + return; + } + Log.p("PushDispatcher: a push waited " + holdLimitMs + "ms for a blocking call " + + "to return and is delivered inside it. Keep blocking calls out of start() and " + + "push(); see Lifecycle.onReady(boolean).", Log.WARNING); + drain(true); + } + + private static void drain(boolean force) { + // Re-checked per push: a delivery that itself blocks (a push handler showing a modal + // Dialog) holds the ones behind it until it returns, as any other blocking call does. + // Never from inside a running delivery either: a drain task pumped by flushEdt() in a + // handler's modal Dialog show would otherwise deliver there. + while (!HELD.isEmpty() && (force || !deferred || (blockingDepth == 0 && deliveryDepth < 0))) { + Runnable next = HELD.remove(0); + boolean ok = false; + try { + run(next); + ok = true; + } finally { + if (!ok && !HELD.isEmpty()) { + // The exception goes on to the EDT's handler as it always did; the pushes + // behind the failed one are still delivered, and still bounded. + scheduleDrain(); + armHoldLimit(Display.getInstance()); + } + } + } + if (HELD.isEmpty()) { + endHoldLimit(); + } + } +} diff --git a/CodenameOne/src/com/codename1/push/Push.java b/CodenameOne/src/com/codename1/push/Push.java index 7f58bbe4b0a..471cd1c92f9 100644 --- a/CodenameOne/src/com/codename1/push/Push.java +++ b/CodenameOne/src/com/codename1/push/Push.java @@ -209,6 +209,35 @@ private static ConnectionRequest createPushMessage(String body, String deviceKey throw new RuntimeException("The old push servers no longer work! Please migrate to the new Push servers!"); } + /// Chooses whether an incoming push may interrupt a blocking call. + /// + /// By default (`true`) a push that arrives while the application is inside a blocking call on + /// the EDT -- a modal `Dialog` shown from `start()`, `invokeAndBlock()`, + /// `NetworkManager.addToQueueAndWait()` -- is held, and `PushCallback.push(String)` is called + /// as soon as the outermost blocking call returns. Pushes are delivered in arrival order and + /// none is dropped. A push is never held longer than about 15 seconds -- below the time iOS allows a + /// background push -- after which it is delivered inside the blocking call after all. This keeps a push from running before the form it needs exists, which is + /// what happens when an application is launched by tapping a notification while `start()` is + /// still showing a dialog or waiting on the network. + /// + /// Pass `false` to deliver every push as soon as it reaches the EDT, even in the middle of a + /// blocking call, as releases before this setting did. Call it from `init(Object)` so it is in + /// force before the first push. + /// + /// #### Parameters + /// + /// - `deferred`: true to hold pushes while a blocking call is in progress + public static void setDeliveryDeferred(boolean deferred) { + com.codename1.impl.PushDispatcher.setDeferred(deferred); + } + + /// #### Returns + /// + /// true if pushes are held while a blocking call is in progress, see `#setDeliveryDeferred(boolean)` + public static boolean isDeliveryDeferred() { + return com.codename1.impl.PushDispatcher.isDeferred(); + } + /// Returns the push device key if the device was previously successfully registered for push /// otherwise returns null /// diff --git a/CodenameOne/src/com/codename1/system/Lifecycle.java b/CodenameOne/src/com/codename1/system/Lifecycle.java index 8b29c39b509..c6367ed9cd3 100644 --- a/CodenameOne/src/com/codename1/system/Lifecycle.java +++ b/CodenameOne/src/com/codename1/system/Lifecycle.java @@ -40,6 +40,7 @@ /// implementations to help keep sample code smaller. public class Lifecycle { private Form current; + private boolean started; private Resources theme; /// Invoked when the app is "cold launched", this acts like a constructor @@ -115,24 +116,76 @@ protected void handleNetworkError(NetworkEvent err) { Dialog.show("Connection Error", "There was a networking error in the connection to " + err.getConnectionRequest().getUrl(), "OK", null); } - /// Default start callback that's invoked on application resume + /// Called by the OS on the first launch and every time the application comes back to the + /// foreground: after `stop()`, when the user taps a notification, or when another application + /// (a provisioning flow, a share sheet, a payment app) brings this one forward. + /// + /// Shows the form the application was on through `#onResume(Form)` when there is one, and calls + /// `#runApp()` otherwise. Either way it then schedules `#onReady(boolean)`, which runs after + /// this method has returned. + /// + /// Do not block here, or in `runApp()` or `onResume(Form)`, which run inside it: no modal + /// `Dialog.show()`, `invokeAndBlock()` or `NetworkManager.addToQueueAndWait()`. The OS expects + /// this method to return, and a push can arrive while it is blocked. The simulator throws a + /// `com.codename1.ui.BlockingDisallowedException` for a blocking call made here so the mistake + /// is found at the line that makes it. Put such code in `onReady(boolean)`. public void start() { + final boolean firstLaunch = !started; + started = true; if (current != null) { - current.show(); - return; + onResume(current); + } else { + runApp(); } - - runApp(); + CN.callSerially(new Runnable() { + @Override + public void run() { + onReady(firstLaunch); + } + }); } - - /// This method is invoked by start to show the first form of the application + /// Shows the first form of the application. Called by `#start()` when there is no form to + /// return to: on the first launch, and on a later start when `stop()` found none. + /// + /// It runs inside `start()`, so it must not block; see `#start()`. Build and show the form + /// here, and do anything that waits -- a login check against the server, an SDK that shows its + /// own dialog, a permission prompt -- in `#onReady(boolean)`. public void runApp() { Form hello = new Form("Hello", BoxLayout.y()); hello.add(new Label("You should override runApp() with your code")); hello.show(); } + /// Called by `#start()` when the application returns to the foreground with a form to + /// return to. The default shows `current` again. Override it to refresh what that form shows, + /// or to route somewhere else, for example back to a login form after a timeout. + /// + /// It runs inside `start()`, so it must not block; see `#start()`. + /// + /// #### Parameters + /// + /// - `current`: the form that was showing when the application was stopped + protected void onResume(Form current) { + current.show(); + } + + /// Called once the application is on screen and `#start()` has returned: after the first + /// launch and after every resume, as its own task on the EDT. + /// + /// This is the place for startup work that waits or shows something on top of the form: + /// validation dialogs, a backend or SDK call, re-authentication when the application + /// returns. Blocking calls are allowed here. Pushes that arrive while such a call is in + /// progress are held until it returns (see `com.codename1.push.Push#setDeliveryDeferred(boolean)`), + /// so a `push()` callback does not run in the middle of it. + /// + /// The default does nothing. + /// + /// #### Parameters + /// + /// - `firstLaunch`: true the first time after the application process started, false on a resume + protected void onReady(boolean firstLaunch) { + } /// Callback when the app is suspended public void stop() { diff --git a/CodenameOne/src/com/codename1/ui/BlockingDisallowedException.java b/CodenameOne/src/com/codename1/ui/BlockingDisallowedException.java index 3aead9c539b..8427d777233 100644 --- a/CodenameOne/src/com/codename1/ui/BlockingDisallowedException.java +++ b/CodenameOne/src/com/codename1/ui/BlockingDisallowedException.java @@ -38,4 +38,13 @@ public class BlockingDisallowedException extends IllegalStateException { public BlockingDisallowedException() { super("Attempt to run invokeAndBlock while blocking is disabled."); } + + /// Creates the exception with a message that explains why blocking is disabled here. + /// + /// #### Parameters + /// + /// - `message`: the explanation shown to the developer + public BlockingDisallowedException(String message) { + super(message); + } } diff --git a/CodenameOne/src/com/codename1/ui/Display.java b/CodenameOne/src/com/codename1/ui/Display.java index 4402380f4ae..8fa33541530 100644 --- a/CodenameOne/src/com/codename1/ui/Display.java +++ b/CodenameOne/src/com/codename1/ui/Display.java @@ -32,6 +32,7 @@ import com.codename1.db.Database; import com.codename1.db.DatabaseConfig; import com.codename1.impl.CodenameOneImplementation; +import com.codename1.impl.PushDispatcher; import com.codename1.impl.CodenameOneThread; import com.codename1.impl.ImplementationFactory; import com.codename1.impl.VirtualKeyboardInterface; @@ -249,6 +250,10 @@ public final class Display extends CN1Constants { /// Tracks whether the initial window size hint has already been consumed for the first shown form. private boolean initialWindowSizeApplied; private boolean disableInvokeAndBlock; + + /// Why blocking is disabled, set by `#invokeWithoutBlocking(java.lang.Runnable, java.lang.String)`; + /// null for the generic message. + private String disableInvokeAndBlockReason; /// Enable Async stack traces. This is disabled by default, but will cause /// stack traces of callSerially() calls to be stored, and logged if the /// Runnable throws an exception. @@ -1367,6 +1372,9 @@ void flushEdt() { if (!isEdt()) { return; } + // Not counted by PushDispatcher, unlike invokeAndBlock: this is a short internal pump, + // not a blocking call application code makes, and counting it would push every held + // delivery past the next EDT turn. while (!shouldEDTSleepNoFormAnimation()) { edtLoopImpl(); } @@ -2149,6 +2157,30 @@ public void invokeWithoutBlocking(Runnable r) { } } + /// Same as `#invokeWithoutBlocking(java.lang.Runnable)`, but a blocking call made inside + /// `r` fails with a `BlockingDisallowedException` carrying `reason` as its message, so the + /// developer is told why blocking is not allowed at that point and what to do instead. + /// + /// #### Parameters + /// + /// - `r`: runnable to run immediately + /// + /// - `reason`: the message of the exception thrown when `r` attempts to block + public void invokeWithoutBlocking(Runnable r, String reason) { + if (disableInvokeAndBlock || !isEdt()) { + r.run(); + } else { + disableInvokeAndBlock = true; + disableInvokeAndBlockReason = reason; + try { + r.run(); + } finally { + disableInvokeAndBlock = false; + disableInvokeAndBlockReason = null; + } + } + } + /// Invokes a RunnableWithResultSync with blocking disabled. If any attempt is made to block /// (i.e. call `#invokeAndBlock(java.lang.Runnable)` from inside this Runnable, /// it will result in a `BlockingDisallowedException` being thrown. @@ -2197,54 +2229,64 @@ public void invokeAndBlock(Runnable r, boolean dropEvents) { try { if (isEdt()) { if (disableInvokeAndBlock) { + if (disableInvokeAndBlockReason != null) { + throw new BlockingDisallowedException(disableInvokeAndBlockReason); + } throw new BlockingDisallowedException(); } - // this class allows a runtime exception to propogate correctly out of the - // internal thread - RunnableWrapper w = new RunnableWrapper(r, 1); - RunnableWrapper.pushToThreadPool(w); + // Pushes are held while any blocking call is in progress on the EDT; see + // PushDispatcher. The matching blockingEnded() is in the inner finally. + PushDispatcher.blockingStarted(); + try { + // this class allows a runtime exception to propogate correctly out of the + // internal thread + RunnableWrapper w = new RunnableWrapper(r, 1); + RunnableWrapper.pushToThreadPool(w); - synchronized (lock) { - // prevent an invoke and block loop from breaking the ongoing event processing - if (inputEventStackPointerTmp > 0) { - inputEventStackPointerTmp = inputEventStackPointer; - } - try { - // yield the CPU for a very short time to let the invoke thread - // get started - lock.wait(2); - } catch (InterruptedException ex) { - ex.printStackTrace(); - } + synchronized (lock) { + // prevent an invoke and block loop from breaking the ongoing event processing + if (inputEventStackPointerTmp > 0) { + inputEventStackPointerTmp = inputEventStackPointer; + } + try { + // yield the CPU for a very short time to let the invoke thread + // get started + lock.wait(2); + } catch (InterruptedException ex) { + ex.printStackTrace(); + } - while (!runningSerialCallsQueue.isEmpty()) { - // Held as an Object and tested: the catch below takes RuntimeException, - // and ParparVM's unchecked cast would never reach it. - Object call = runningSerialCallsQueue.removeLast(); - if (call instanceof Runnable) { - pendingSerialCalls.add(0, (Runnable) call); + while (!runningSerialCallsQueue.isEmpty()) { + // Held as an Object and tested: the catch below takes RuntimeException, + // and ParparVM's unchecked cast would never reach it. + Object call = runningSerialCallsQueue.removeLast(); + if (call instanceof Runnable) { + pendingSerialCalls.add(0, (Runnable) call); + } } } - } - // loop over the EDT until the thread completes then return - while (!w.isDone() && codenameOneRunning) { - edtLoopImpl(); - synchronized (lock) { - if (shouldEDTSleep()) { - impl.edtIdle(true); - try { - lock.wait(10); - } catch (InterruptedException ex) { + // loop over the EDT until the thread completes then return + while (!w.isDone() && codenameOneRunning) { + edtLoopImpl(); + synchronized (lock) { + if (shouldEDTSleep()) { + impl.edtIdle(true); + try { + lock.wait(10); + } catch (InterruptedException ex) { + } + impl.edtIdle(false); } - impl.edtIdle(false); } } - } - // if the thread thew an exception we need to throw it onwards - if (w.getErr() != null) { - throw w.getErr(); + // if the thread thew an exception we need to throw it onwards + if (w.getErr() != null) { + throw w.getErr(); + } + } finally { + PushDispatcher.blockingEnded(); } } else { r.run(); diff --git a/Ports/Android/src/com/codename1/impl/android/AndroidImplementation.java b/Ports/Android/src/com/codename1/impl/android/AndroidImplementation.java index f50dca530aa..d427816e37f 100644 --- a/Ports/Android/src/com/codename1/impl/android/AndroidImplementation.java +++ b/Ports/Android/src/com/codename1/impl/android/AndroidImplementation.java @@ -1550,7 +1550,10 @@ public static void firePendingPushes(final PushCallback c, final Context a) { image = null; } long s = is.readLong(); - Display.getInstance().callSerially(new Runnable() { + // PushDispatcher, not callSerially: held while a blocking call (a modal + // Dialog in start()) is in progress, which is when a notification tap + // that launched the app would otherwise be delivered. + com.codename1.impl.PushDispatcher.dispatch(new Runnable() { @Override public void run() { Display.getInstance().setProperty("pendingPush", "true"); diff --git a/Ports/Android/src/com/codename1/impl/android/PushNotificationService.java b/Ports/Android/src/com/codename1/impl/android/PushNotificationService.java index 38e487dfc5d..b10b7089bdf 100644 --- a/Ports/Android/src/com/codename1/impl/android/PushNotificationService.java +++ b/Ports/Android/src/com/codename1/impl/android/PushNotificationService.java @@ -112,7 +112,9 @@ public void push(final String value) { if (delayPushCompletion) { AndroidImplementation.acquirePushWakeLock(30000); } - Display.getInstance().callSerially(new Runnable() { + // PushDispatcher, not callSerially: it marshals to the EDT the same way, and holds + // the delivery while a blocking call (a modal Dialog in start()) is in progress. + com.codename1.impl.PushDispatcher.dispatch(new Runnable() { public void run() { try { callback.push(value); diff --git a/Ports/JavaSE/src/com/codename1/impl/javase/Executor.java b/Ports/JavaSE/src/com/codename1/impl/javase/Executor.java index a7e57aa5d88..4cc09afcbf3 100644 --- a/Ports/JavaSE/src/com/codename1/impl/javase/Executor.java +++ b/Ports/JavaSE/src/com/codename1/impl/javase/Executor.java @@ -369,13 +369,13 @@ public void run() { // com.codename1.generated.svg.SVGRegistry reflectively // when it's on the classpath, so no per-Executor // install is needed here. - m.invoke(app, new Object[]{null}); + invokeLifecycle(m, "init(Object)", new Object[]{null}); Method start = c.getMethod("start", new Class[0]); if(start.getExceptionTypes() != null && start.getExceptionTypes().length > 0) { System.err.println("ERROR: the start method can't declare a throws clause"); System.exit(1); } - start.invoke(app, new Object[0]); + invokeLifecycle(start, "start()", new Object[0]); } catch (NoSuchMethodException err) { System.out.println("Couldn't find a main or a startup in " + argv[0]); } catch (InvocationTargetException err) { @@ -445,7 +445,7 @@ public static void stopApp(){ System.err.println("ERROR: the stop method can't declare a throws clause"); System.exit(1); } - stop.invoke(app, new Object[0]); + invokeLifecycle(stop, "stop()", new Object[0]); } catch (Exception ex) { ex.printStackTrace(); } @@ -493,11 +493,54 @@ public static void cleanupForSimulatorReload() { } } + /// The simulator runs every lifecycle callback with blocking disabled, so a modal Dialog, + /// invokeAndBlock() or addToQueueAndWait() inside one fails here, at the line that does it, + /// instead of racing the platform on a device. + /// + /// On a phone the OS calls these methods itself and expects them to return: start() is also + /// how a notification tap or a provisioning intent brings the app forward, and a push can + /// arrive while start() is still blocked. Code that blocks there works in the simulator and + /// crashes intermittently on devices, which is the hardest kind of bug to diagnose -- so the + /// simulator refuses it outright rather than warning. + /// + /// Off the EDT invokeWithoutBlocking cannot guard anything (invokeAndBlock does not block + /// there), so the call simply runs. That is the case for stop() and destroy(), which the + /// simulator calls from the Swing thread; they go through here so they are covered the day + /// they move onto the EDT, and the message names only the callbacks actually guarded. + static Object invokeLifecycle(final Method m, final String name, final Object[] args) throws Exception { + final Object[] result = new Object[1]; + final Exception[] err = new Exception[1]; + Display.getInstance().invokeWithoutBlocking(new Runnable() { + @Override + public void run() { + try { + result[0] = m.invoke(app, args); + } catch (Exception ex) { + err[0] = ex; + } + } + }, lifecycleBlockingMessage(name)); + if (err[0] != null) { + throw err[0]; + } + return result[0]; + } + + static String lifecycleBlockingMessage(String name) { + return "A blocking call was made inside " + name + ". Modal Dialog.show(), " + + "invokeAndBlock(), NetworkManager.addToQueueAndWait() and other blocking calls " + + "are not allowed in the lifecycle methods init and start: the OS " + + "calls them on every launch and resume, including when a notification or another " + + "app brings yours forward, and a push can arrive while they are blocked. Such code " + + "fails intermittently on devices. Move it to Lifecycle.onReady(boolean), which runs " + + "after start() returns, or schedule it with CN.callSerially()."; + } + public static void destroyApp(){ if(c != null && app != null){ try { Method stop = c.getMethod("destroy", new Class[0]); - stop.invoke(app, new Object[0]); + invokeLifecycle(stop, "destroy()", new Object[0]); } catch (Exception ex) { ex.printStackTrace(); } @@ -515,7 +558,7 @@ public void run() { System.err.println("ERROR: the start method can't declare a throws clause"); System.exit(1); } - start.invoke(app, new Object[0]); + invokeLifecycle(start, "start()", new Object[0]); } catch (Exception ex) { ex.printStackTrace(); } @@ -564,7 +607,9 @@ public void run() { public static void push(final String message, final int type){ if(c != null && app != null){ - Display.getInstance().callSerially(new Runnable() { + // Through PushDispatcher, as on the devices, so the simulator holds a push while a + // blocking call is in progress exactly as a phone does. + com.codename1.impl.PushDispatcher.dispatch(new Runnable() { @Override public void run() { try { diff --git a/Ports/JavaScriptPort/src/main/java/com/codename1/impl/html5/HTML5Push.java b/Ports/JavaScriptPort/src/main/java/com/codename1/impl/html5/HTML5Push.java index aabcef4fb09..c6758837ba7 100644 --- a/Ports/JavaScriptPort/src/main/java/com/codename1/impl/html5/HTML5Push.java +++ b/Ports/JavaScriptPort/src/main/java/com/codename1/impl/html5/HTML5Push.java @@ -177,7 +177,19 @@ public void run() { @Override public void onPush(final JSObject data) { if (typedEnvelope) { - typedCallback.push(stringify(data)); + // Onto the EDT and through PushDispatcher like every other port, so a push + // that lands during a blocking call (a modal Dialog in start()) is held + // until it returns. The payload is read here, in the browser callback. + final String body = stringify(data); + HTML5Implementation.callSerially(new Runnable() { + public void run() { + com.codename1.impl.PushDispatcher.dispatch(new Runnable() { + public void run() { + typedCallback.push(body); + } + }); + } + }); return; } //System.out.println("In onPush"); @@ -247,10 +259,14 @@ public void run() { final String message = _message; HTML5Implementation.callSerially(new Runnable() { public void run() { - //System.out.println("Now on EDT about to call _pushReceived"); - Display.getInstance().setProperty("pushType", pushType); - initPushContent(message, image, String.valueOf(messageType), dataCategory, dataAction); - HTML5Implementation.getInstance()._pushReceived(message); + // Held by PushDispatcher while a blocking call is in progress. + com.codename1.impl.PushDispatcher.dispatch(new Runnable() { + public void run() { + Display.getInstance().setProperty("pushType", pushType); + initPushContent(message, image, String.valueOf(messageType), dataCategory, dataAction); + HTML5Implementation.getInstance()._pushReceived(message); + } + }); } }); } diff --git a/Ports/iOSPort/src/com/codename1/impl/ios/IOSImplementation.java b/Ports/iOSPort/src/com/codename1/impl/ios/IOSImplementation.java index 90aa23e4cfd..fdee381e324 100644 --- a/Ports/iOSPort/src/com/codename1/impl/ios/IOSImplementation.java +++ b/Ports/iOSPort/src/com/codename1/impl/ios/IOSImplementation.java @@ -13902,7 +13902,9 @@ private static void pushReceived(final String message, final String type, final long completionId, final boolean restore, final PushContent content) { if(pushCallback != null) { - Display.getInstance().callSerially(new Runnable() { + // PushDispatcher, not callSerially: it marshals to the EDT the same way, and holds + // the delivery while a blocking call (a modal Dialog in start()) is in progress. + com.codename1.impl.PushDispatcher.dispatch(new Runnable() { public void run() { try { if (restore) { diff --git a/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/LifecycleOnReadySnippet.java b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/LifecycleOnReadySnippet.java new file mode 100644 index 00000000000..c001e8c11ff --- /dev/null +++ b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/LifecycleOnReadySnippet.java @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ + +package com.codenameone.developerguide.snippets; + +import com.codename1.io.Preferences; +import com.codename1.system.Lifecycle; +import com.codename1.ui.Dialog; + +class LifecycleOnReadySnippet { + // tag::lifecycle-on-ready[] + public class MyApp extends Lifecycle { + @Override + protected void onReady(boolean firstLaunch) { + long lastSeen = Preferences.get("lastSeen", 0L); + Preferences.set("lastSeen", System.currentTimeMillis()); + if (!firstLaunch && System.currentTimeMillis() - lastSeen > 30 * 60000L) { + // a modal dialog is allowed here, start() has already returned + Dialog.show("Session expired", "Please sign in again", "OK", null); + } + } + } + // end::lifecycle-on-ready[] +} diff --git a/docs/developer-guide/Introduction.asciidoc b/docs/developer-guide/Introduction.asciidoc index c88c5152d21..b6374a1cdb6 100644 --- a/docs/developer-guide/Introduction.asciidoc +++ b/docs/developer-guide/Introduction.asciidoc @@ -330,9 +330,11 @@ the generated class carries none of them: * `init(Object)` sets the network thread count, installs the theme, turns on the global `Toolbar`, binds crash protection through `Log.bindCrashProtection` and registers a network error listener, in that order. -* `start()` calls `runApp()` on a cold start. On a warm start it re-shows the - `Form` the user was looking at when the app was suspended, so returning to an app - lands the user back where they were. +* `start()` calls `runApp()` on a cold start. On a warm start it calls + `onResume(Form)`, which by default re-shows the `Form` the user was looking at + when the app was suspended, so returning to an app lands the user back where they + were. Either way it then schedules `onReady(boolean)`, which runs after `start()` + has returned. * `stop()` remembers that `Form`, disposing a `Dialog` first so the app doesn't come back to a modal. * `destroy()` does nothing by default. @@ -396,6 +398,39 @@ user would hate to lose. <3> The other half of that: `runApp` puts the saved draft back, so the pair survives the app being killed while suspended. +[[LifecycleNoBlocking]] +===== Never block inside a lifecycle callback + +`start()` isn't only the app launching. On a phone the OS calls it whenever the +app comes back to the foreground, and that includes the user tapping a +notification, a provisioning flow handing control back, or another app returning +from a share or a payment. A push can arrive while `start()` is still running. A +modal `Dialog.show()`, an `invokeAndBlock()` or a +`NetworkManager.addToQueueAndWait()` inside `start()` leaves the OS waiting while +the push lands in the middle of your startup code, usually before the login form +exists. The symptom is a crash that comes and goes, and which a delay seems to +fix, sometimes. + +The simulator therefore refuses it. A blocking call inside `init` or `start` (and so +inside `runApp()` and `onResume(Form)`, which `start()` calls) throws a `BlockingDisallowedException` that names the callback and fails the run +at the line that blocked. + +Startup work that waits belongs in `onReady(boolean)`. `Lifecycle` calls it as a +task of its own once `start()` has returned, on the first launch (`true`) and on +every resume (`false`). Blocking there is fine: + +[source,java] +---- +include::../demos/common/src/main/java/com/codenameone/developerguide/snippets/LifecycleOnReadySnippet.java[tag=lifecycle-on-ready,indent=0] +---- + +Pushes wait for blocking calls too. A push that arrives while any blocking call is +in progress on the EDT, in `onReady` or anywhere else, is held, and `push()` is +called once the outermost blocking call returns. Pushes arrive in order, none is +dropped, and none is held longer than about 15 seconds, which keeps a background +push inside the time iOS allows it. To get the old behaviour back, call +`Push.setDeliveryDeferred(false)` from `init(Object)`. + That's it. You should now have a general sense of the code. It's time to run on the device. ==== Building and deploying on devices diff --git a/docs/developer-guide/Push-Notifications.asciidoc b/docs/developer-guide/Push-Notifications.asciidoc index f1d315aaa2b..a8feef5b343 100644 --- a/docs/developer-guide/Push-Notifications.asciidoc +++ b/docs/developer-guide/Push-Notifications.asciidoc @@ -104,6 +104,8 @@ Every `PushListener` and `PushRegistrationSink` callback runs on the Codename On * `onMessage()` receives one parsed schema-3 envelope. A foreground notification can arrive immediately. A visible background notification normally arrives after the user opens it. * `onError()` reports registration and envelope errors. Use `PushError.getCode()` for decisions; diagnostic text isn't a stable contract. +A message that arrives while the application is inside a blocking call on the EDT, such as a modal `Dialog` or `invokeAndBlock()`, is held until that call returns, so a notification tap that launches the app can't run its listener in the middle of startup code. `Push.setDeliveryDeferred(false)` turns this off; see <>. + Native ports preserve a cold-start notification until the runtime can deliver it. If the runtime starts before the application calls `register()`, `PushClient` keeps a bounded process-local queue and replays it after activation. If the application never registers its client, it has provided no listener and can't expect application callbacks. Silent/background execution remains subject to each OS's power and scheduling rules, so refresh authoritative state whenever the application resumes. === Build a message diff --git a/maven/core-unittests/spotbugs-exclude.xml b/maven/core-unittests/spotbugs-exclude.xml index 5764dc82656..077caf4bed4 100644 --- a/maven/core-unittests/spotbugs-exclude.xml +++ b/maven/core-unittests/spotbugs-exclude.xml @@ -488,4 +488,12 @@ + + + + + + diff --git a/maven/core-unittests/src/test/java/com/codename1/impl/PushDispatcherTest.java b/maven/core-unittests/src/test/java/com/codename1/impl/PushDispatcherTest.java new file mode 100644 index 00000000000..7b4fbe20432 --- /dev/null +++ b/maven/core-unittests/src/test/java/com/codename1/impl/PushDispatcherTest.java @@ -0,0 +1,306 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.impl; + +import com.codename1.junit.FormTest; +import com.codename1.junit.UITestBase; +import com.codename1.push.Push; +import com.codename1.push.PushContent; +import com.codename1.ui.BlockingDisallowedException; +import com.codename1.ui.Display; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PushDispatcherTest extends UITestBase { + + private Runnable record(final List log, final String name) { + return new Runnable() { + @Override + public void run() { + log.add(name); + } + }; + } + + @FormTest + void deliversImmediatelyWhenNothingBlocks() { + List log = new ArrayList(); + PushDispatcher.dispatch(record(log, "a")); + assertEquals(1, log.size(), "with no blocking call in progress the push runs at once"); + } + + @FormTest + void holdsWhileBlockingAndDeliversInOrderAfterwards() { + List log = new ArrayList(); + PushDispatcher.blockingStarted(); + try { + PushDispatcher.dispatch(record(log, "a")); + PushDispatcher.dispatch(record(log, "b")); + flushSerialCalls(); + assertTrue(log.isEmpty(), "held while a blocking call is in progress"); + } finally { + PushDispatcher.blockingEnded(); + } + assertTrue(log.isEmpty(), "delivered as a fresh EDT task, not from inside blockingEnded"); + flushSerialCalls(); + assertEquals("[a, b]", log.toString()); + } + + @FormTest + void nestedBlockingReleasesOnlyAtTheOutermost() { + List log = new ArrayList(); + PushDispatcher.blockingStarted(); + PushDispatcher.blockingStarted(); + PushDispatcher.dispatch(record(log, "a")); + PushDispatcher.blockingEnded(); + flushSerialCalls(); + assertTrue(log.isEmpty(), "still inside the outer blocking call"); + PushDispatcher.blockingEnded(); + flushSerialCalls(); + assertEquals("[a]", log.toString()); + } + + @FormTest + void laterPushWaitsBehindHeldOnes() { + List log = new ArrayList(); + PushDispatcher.blockingStarted(); + PushDispatcher.dispatch(record(log, "a")); + PushDispatcher.blockingEnded(); + // The drain is queued but has not run; a push arriving now must not overtake "a". + PushDispatcher.dispatch(record(log, "b")); + flushSerialCalls(); + assertEquals("[a, b]", log.toString()); + } + + @FormTest + void deferralCanBeSwitchedOff() { + List log = new ArrayList(); + Push.setDeliveryDeferred(false); + try { + assertFalse(Push.isDeliveryDeferred()); + PushDispatcher.blockingStarted(); + try { + PushDispatcher.dispatch(record(log, "a")); + assertEquals("[a]", log.toString(), "off, a push runs even inside a blocking call"); + } finally { + PushDispatcher.blockingEnded(); + } + } finally { + Push.setDeliveryDeferred(true); + } + assertTrue(Push.isDeliveryDeferred()); + } + + @FormTest + void switchingOffReleasesWhatIsHeld() { + List log = new ArrayList(); + PushDispatcher.blockingStarted(); + try { + PushDispatcher.dispatch(record(log, "a")); + Push.setDeliveryDeferred(false); + flushSerialCalls(); + assertEquals("[a]", log.toString()); + } finally { + Push.setDeliveryDeferred(true); + PushDispatcher.blockingEnded(); + } + } + + @FormTest + void aRealInvokeAndBlockHoldsAPushThatArrivesDuringIt() { + final List log = new ArrayList(); + Display.getInstance().invokeAndBlock(new Runnable() { + @Override + public void run() { + // The worker thread: dispatch marshals to the EDT, which is busy in the nested + // loop of this very invokeAndBlock. Wait until that loop has handled it. + PushDispatcher.dispatch(record(log, "a")); + try { + Thread.sleep(200); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + } + }); + assertTrue(log.isEmpty(), "not delivered inside the blocking call"); + flushSerialCalls(); + assertEquals("[a]", log.toString()); + } + + @FormTest + void aFailingDeliveryDoesNotStrandThoseBehindIt() { + List log = new ArrayList(); + PushDispatcher.blockingStarted(); + PushDispatcher.dispatch(new Runnable() { + @Override + public void run() { + throw new IllegalStateException("boom"); + } + }); + PushDispatcher.dispatch(record(log, "b")); + PushDispatcher.blockingEnded(); + try { + flushSerialCalls(); + } catch (RuntimeException expected) { + // the failure reaches the EDT's handler as before + } + flushSerialCalls(); + assertEquals("[b]", log.toString()); + } + + @FormTest + void theHoldLimitDeliversInsideAStuckBlockingCall() throws Exception { + List log = new ArrayList(); + int saved = PushDispatcher.holdLimitMs; + PushDispatcher.holdLimitMs = 50; + PushDispatcher.blockingStarted(); + try { + PushDispatcher.dispatch(record(log, "a")); + long deadline = System.currentTimeMillis() + 3000; + while (log.isEmpty() && System.currentTimeMillis() < deadline) { + Thread.sleep(20); + flushSerialCalls(); + } + assertEquals("[a]", log.toString(), "a push is never held past the limit"); + } finally { + PushDispatcher.blockingEnded(); + PushDispatcher.holdLimitMs = saved; + } + } + + @FormTest + void blockingDisallowedCarriesTheReason() { + final String reason = "no blocking in start()"; + BlockingDisallowedException ex = assertThrows(BlockingDisallowedException.class, () -> + Display.getInstance().invokeWithoutBlocking(new Runnable() { + @Override + public void run() { + Display.getInstance().invokeAndBlock(new Runnable() { + @Override + public void run() { + } + }); + } + }, reason)); + assertEquals(reason, ex.getMessage()); + // and blocking works again afterwards, with no stale reason + final boolean[] ran = new boolean[1]; + Display.getInstance().invokeAndBlock(new Runnable() { + @Override + public void run() { + ran[0] = true; + } + }); + assertTrue(ran[0]); + } + + @FormTest + void aHeldPushKeepsItsOwnContent() { + final List log = new ArrayList(); + Runnable reader = new Runnable() { + @Override + public void run() { + PushContent c = PushContent.get(); + log.add((c == null ? "none" : c.getBody()) + "/" + Display.getInstance().getProperty("pushType", null)); + } + }; + PushDispatcher.blockingStarted(); + try { + PushContent.setBody("first"); + Display.getInstance().setProperty("pushType", "1"); + PushDispatcher.dispatch(reader); + // the port writes the globals for the next push before the first is delivered + PushContent.setBody("second"); + Display.getInstance().setProperty("pushType", "2"); + PushDispatcher.dispatch(reader); + } finally { + PushDispatcher.blockingEnded(); + } + flushSerialCalls(); + assertEquals("[first/1, second/2]", log.toString()); + Display.getInstance().setProperty("pushType", null); + PushContent.reset(); + } + + @FormTest + void aPushArrivingDuringADeliveryWaitsForIt() { + // flushEdt() inside a modal Dialog's show pumps serial calls before invokeAndBlock raises + // the blocking depth, so a new push can reach dispatch at depth 0 inside a handler. + final List log = new ArrayList(); + PushDispatcher.blockingStarted(); + PushDispatcher.dispatch(new Runnable() { + @Override + public void run() { + PushDispatcher.dispatch(record(log, "b")); + log.add("a"); + } + }); + PushDispatcher.dispatch(record(log, "c")); + PushDispatcher.blockingEnded(); + flushSerialCalls(); + assertEquals("[a, c, b]", log.toString(), "held pushes keep their order, the newcomer goes last"); + } + + @FormTest + void aPushArrivingDuringAnImmediateDeliveryRunsAfterIt() { + final List log = new ArrayList(); + PushDispatcher.dispatch(new Runnable() { + @Override + public void run() { + PushDispatcher.dispatch(record(log, "b")); + assertTrue(PushDispatcher.isDelivering()); + log.add("a"); + } + }); + flushSerialCalls(); + assertEquals("[a, b]", log.toString()); + assertFalse(PushDispatcher.isDelivering()); + } + + @FormTest + void aNewPushIsHeldWhileAPushHandlerBlocks() { + final List log = new ArrayList(); + PushDispatcher.dispatch(new Runnable() { + @Override + public void run() { + // the handler blocks (a modal Dialog) and a new push reaches the EDT meanwhile + PushDispatcher.blockingStarted(); + try { + PushDispatcher.dispatch(record(log, "c")); + log.add("a-blocked"); + } finally { + PushDispatcher.blockingEnded(); + } + log.add("a-done"); + } + }); + flushSerialCalls(); + assertEquals("[a-blocked, a-done, c]", log.toString()); + } +} diff --git a/maven/core-unittests/src/test/java/com/codename1/system/LifecycleTest.java b/maven/core-unittests/src/test/java/com/codename1/system/LifecycleTest.java new file mode 100644 index 00000000000..d3e4fb2a587 --- /dev/null +++ b/maven/core-unittests/src/test/java/com/codename1/system/LifecycleTest.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Codename One designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Codename One through http://www.codenameone.com/ if you + * need additional information or have any questions. + */ +package com.codename1.system; + +import com.codename1.junit.FormTest; +import com.codename1.junit.UITestBase; +import com.codename1.ui.CN; +import com.codename1.ui.Form; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; + +class LifecycleTest extends UITestBase { + + static class Recording extends Lifecycle { + final List log = new ArrayList(); + Form resumedWith; + + @Override + public void runApp() { + log.add("runApp"); + new Form("Main").show(); + } + + @Override + protected void onResume(Form current) { + log.add("onResume"); + resumedWith = current; + super.onResume(current); + } + + @Override + protected void onReady(boolean firstLaunch) { + log.add("onReady(" + firstLaunch + ")"); + } + } + + @FormTest + void onReadyRunsAfterStartReturnsOnFirstLaunchAndResume() { + Recording app = new Recording(); + app.start(); + app.log.add("start returned"); + flushSerialCalls(); + assertEquals("[runApp, start returned, onReady(true)]", app.log.toString()); + + Form main = CN.getCurrentForm(); + app.stop(); + app.log.clear(); + app.start(); + app.log.add("start returned"); + flushSerialCalls(); + assertEquals("[onResume, start returned, onReady(false)]", app.log.toString()); + assertSame(main, app.resumedWith); + } +}