From ceca585cf62db35d354fbb31db4d34cdc983f423 Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:44:30 +0200 Subject: [PATCH 1/9] Lifecycle: no blocking in start(), pushes wait for blocking calls, onReady/onResume The simulator runs init/start/stop/destroy with blocking disabled and a BlockingDisallowedException that names the callback. Pushes on every port go through PushDispatcher, which holds them while a blocking call is in progress on the EDT (at most 20s); Push.setDeliveryDeferred(false) restores direct delivery. Lifecycle gains onResume(Form) and onReady(boolean), which runs after start() returns and is where blocking startup work belongs. Co-Authored-By: Claude Opus 5.5 --- .../com/codename1/impl/PushDispatcher.java | 208 +++++++++++++++++ CodenameOne/src/com/codename1/push/Push.java | 29 +++ .../src/com/codename1/system/Lifecycle.java | 67 +++++- .../ui/BlockingDisallowedException.java | 9 + CodenameOne/src/com/codename1/ui/Display.java | 113 ++++++--- .../impl/android/AndroidImplementation.java | 5 +- .../impl/android/PushNotificationService.java | 4 +- .../com/codename1/impl/javase/Executor.java | 55 ++++- .../com/codename1/impl/html5/HTML5Push.java | 26 ++- .../codename1/impl/ios/IOSImplementation.java | 4 +- docs/developer-guide/Introduction.asciidoc | 49 +++- .../Push-Notifications.asciidoc | 2 + .../codename1/impl/PushDispatcherTest.java | 221 ++++++++++++++++++ .../com/codename1/system/LifecycleTest.java | 78 +++++++ 14 files changed, 809 insertions(+), 61 deletions(-) create mode 100644 CodenameOne/src/com/codename1/impl/PushDispatcher.java create mode 100644 maven/core-unittests/src/test/java/com/codename1/impl/PushDispatcherTest.java create mode 100644 maven/core-unittests/src/test/java/com/codename1/system/LifecycleTest.java diff --git a/CodenameOne/src/com/codename1/impl/PushDispatcher.java b/CodenameOne/src/com/codename1/impl/PushDispatcher.java new file mode 100644 index 00000000000..41be46686e5 --- /dev/null +++ b/CodenameOne/src/com/codename1/impl/PushDispatcher.java @@ -0,0 +1,208 @@ +/* + * 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.ui.Display; + +import com.codename1.io.Log; + +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 20 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. +/// +/// 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; + private static boolean deferred = true; + private static boolean drainScheduled; + + /// The longest a push is held, in milliseconds. Below the time the OS allows a background + /// push before it must report completion (about 30 seconds on iOS), so that a dialog left + /// open when the user switched away cannot get the application killed or a wake lock leaked. + static final int MAX_HOLD_MS = 20000; + + /// The limit in force; `#MAX_HOLD_MS` except in tests, which cannot wait 20 seconds. + static int holdLimitMs = MAX_HOLD_MS; + + private static Timer holdLimit; + + 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 still delivered. + /// + /// #### 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; + } + if (!deferred || (blockingDepth == 0 && HELD.isEmpty())) { + delivery.run(); + return; + } + HELD.add(delivery); + if (holdLimit == null) { + holdLimit = d.setTimeout(holdLimitMs, new Runnable() { + @Override + public void run() { + holdLimit = null; + deliverHeldNow(); + } + }); + } + 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 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(); + } + }); + } + + private static void drain() { + // 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. + while (!HELD.isEmpty() && (blockingDepth == 0 || !deferred)) { + Runnable next = HELD.remove(0); + boolean ok = false; + try { + next.run(); + 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. + scheduleDrain(); + } + } + } + cancelHoldLimitIfEmpty(); + } + + /// 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); + while (!HELD.isEmpty()) { + Runnable next = HELD.remove(0); + boolean ok = false; + try { + next.run(); + ok = true; + } finally { + if (!ok && !HELD.isEmpty()) { + scheduleDrain(); + } + } + } + } + + private static void cancelHoldLimitIfEmpty() { + if (HELD.isEmpty() && holdLimit != null) { + holdLimit.cancel(); + holdLimit = null; + } + } +} diff --git a/CodenameOne/src/com/codename1/push/Push.java b/CodenameOne/src/com/codename1/push/Push.java index 7f58bbe4b0a..786939f005d 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 20 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..6b47990f354 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. @@ -2149,6 +2154,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 +2226,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..1222c9eeeaa 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,52 @@ 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. + 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, start, stop, destroy): 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 +556,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 +605,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/developer-guide/Introduction.asciidoc b/docs/developer-guide/Introduction.asciidoc index c88c5152d21..5b4da404933 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,47 @@ 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()` is not 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. + +So the simulator refuses it. A blocking call inside `init`, `start`, `stop` or +`destroy` (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] +---- +@Override +protected void onReady(boolean firstLaunch) { + if (!firstLaunch && sessionExpired()) { + // a modal dialog is allowed here, start() has already returned + Dialog.show("Session expired", "Please sign in again", "OK", null); + new LoginForm().show(); + } +} +---- + +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 20 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/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..70c649dab09 --- /dev/null +++ b/maven/core-unittests/src/test/java/com/codename1/impl/PushDispatcherTest.java @@ -0,0 +1,221 @@ +/* + * 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.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]); + } +} 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); + } +} From 002279eadbbed80b4ce7bac8ef8846c901e5a348 Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:49:36 +0200 Subject: [PATCH 2/9] PushDispatcher: per-hold PushContent, timer token, 15s cap, legacy path Co-Authored-By: Claude Opus 5.5 --- .../impl/CodenameOneImplementation.java | 12 +- .../com/codename1/impl/PushDispatcher.java | 160 ++++++++++++------ CodenameOne/src/com/codename1/push/Push.java | 2 +- .../com/codename1/impl/javase/Executor.java | 6 +- docs/developer-guide/Introduction.asciidoc | 9 +- .../codename1/impl/PushDispatcherTest.java | 46 +++++ 6 files changed, 174 insertions(+), 61 deletions(-) diff --git a/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java b/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java index 1df1978dc49..8aa9b38af77 100644 --- a/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java +++ b/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java @@ -11081,9 +11081,17 @@ protected final void sendRegisteredForPush(String id) { } } - protected final void pushReceived(String data) { + protected final void pushReceived(final String data) { if (callback != null) { - callback.push(data); + // Through PushDispatcher like every port path, so a push is held while a + // blocking call is in progress. Inline when already inside a delivery. + final PushCallback c = callback; + PushDispatcher.dispatch(new Runnable() { + @Override + public void run() { + c.push(data); + } + }); } } diff --git a/CodenameOne/src/com/codename1/impl/PushDispatcher.java b/CodenameOne/src/com/codename1/impl/PushDispatcher.java index 41be46686e5..9cb7e72fcd7 100644 --- a/CodenameOne/src/com/codename1/impl/PushDispatcher.java +++ b/CodenameOne/src/com/codename1/impl/PushDispatcher.java @@ -22,9 +22,9 @@ */ package com.codename1.impl; -import com.codename1.ui.Display; - import com.codename1.io.Log; +import com.codename1.push.PushContent; +import com.codename1.ui.Display; import java.util.ArrayList; import java.util.Timer; @@ -40,10 +40,14 @@ /// 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 20 seconds, so a dialog left open while +/// 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): 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. +/// /// 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 @@ -53,24 +57,30 @@ public final class PushDispatcher { private static final ArrayList HELD = new ArrayList(); private static int blockingDepth; + private static int delivering; private static boolean deferred = true; private static boolean drainScheduled; - /// The longest a push is held, in milliseconds. Below the time the OS allows a background - /// push before it must report completion (about 30 seconds on iOS), so that a dialog left - /// open when the user switched away cannot get the application killed or a wake lock leaked. - static final int MAX_HOLD_MS = 20000; + /// 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 20 seconds. + /// The limit in force; `#MAX_HOLD_MS` except in tests, which cannot wait that long. static int holdLimitMs = MAX_HOLD_MS; - private static Timer holdLimit; + /// 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 token it was armed + /// with and does nothing unless it is still the current one. + private static Object holdToken; + 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 still delivered. + /// reaches the EDT, even inside a blocking call. Pushes already held are then delivered too. /// /// #### Parameters /// @@ -106,20 +116,14 @@ public void run() { }); return; } - if (!deferred || (blockingDepth == 0 && HELD.isEmpty())) { - delivery.run(); + // A delivery that dispatches again (a port path that ends in the generic pushReceived) + // is the same push: run it in place rather than queue it behind later ones. + if (delivering > 0 || !deferred || (blockingDepth == 0 && HELD.isEmpty())) { + run(delivery); return; } - HELD.add(delivery); - if (holdLimit == null) { - holdLimit = d.setTimeout(holdLimitMs, new Runnable() { - @Override - public void run() { - holdLimit = null; - deliverHeldNow(); - } - }); - } + HELD.add(withContent(delivery)); + armHoldLimit(d); if (blockingDepth == 0) { scheduleDrain(); } @@ -140,6 +144,75 @@ public static void blockingEnded() { } } + private static void run(Runnable delivery) { + delivering++; + try { + delivery.run(); + } finally { + delivering--; + } + } + + /// 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(); + } + }; + } + + private static void restore(PushContent c, String pushType) { + 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()); + PushContent.setType(c.getType()); + } + + private static void armHoldLimit(Display d) { + if (holdToken != null) { + return; + } + final Object token = new Object(); + holdToken = token; + holdTimer = d.setTimeout(holdLimitMs, new Runnable() { + @Override + public void run() { + if (holdToken != token) { + 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() { + holdToken = null; + if (holdTimer != null) { + holdTimer.cancel(); + holdTimer = null; + } + } + private static void scheduleDrain() { if (drainScheduled) { return; @@ -151,31 +224,11 @@ private static void scheduleDrain() { @Override public void run() { drainScheduled = false; - drain(); + drain(false); } }); } - private static void drain() { - // 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. - while (!HELD.isEmpty() && (blockingDepth == 0 || !deferred)) { - Runnable next = HELD.remove(0); - boolean ok = false; - try { - next.run(); - 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. - scheduleDrain(); - } - } - } - cancelHoldLimitIfEmpty(); - } - /// 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() { @@ -185,24 +238,29 @@ private static void deliverHeldNow() { 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); - while (!HELD.isEmpty()) { + 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. + while (!HELD.isEmpty() && (force || blockingDepth == 0 || !deferred)) { Runnable next = HELD.remove(0); boolean ok = false; try { - next.run(); + 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()); } } } - } - - private static void cancelHoldLimitIfEmpty() { - if (HELD.isEmpty() && holdLimit != null) { - holdLimit.cancel(); - holdLimit = null; + if (HELD.isEmpty()) { + endHoldLimit(); } } } diff --git a/CodenameOne/src/com/codename1/push/Push.java b/CodenameOne/src/com/codename1/push/Push.java index 786939f005d..471cd1c92f9 100644 --- a/CodenameOne/src/com/codename1/push/Push.java +++ b/CodenameOne/src/com/codename1/push/Push.java @@ -215,7 +215,7 @@ private static ConnectionRequest createPushMessage(String body, String deviceKey /// 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 20 seconds -- below the time iOS allows a + /// 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. diff --git a/Ports/JavaSE/src/com/codename1/impl/javase/Executor.java b/Ports/JavaSE/src/com/codename1/impl/javase/Executor.java index 1222c9eeeaa..4cc09afcbf3 100644 --- a/Ports/JavaSE/src/com/codename1/impl/javase/Executor.java +++ b/Ports/JavaSE/src/com/codename1/impl/javase/Executor.java @@ -504,7 +504,9 @@ public static void cleanupForSimulatorReload() { /// simulator refuses it outright rather than warning. /// /// Off the EDT invokeWithoutBlocking cannot guard anything (invokeAndBlock does not block - /// there), so the call simply runs. + /// 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]; @@ -527,7 +529,7 @@ public void run() { 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, start, stop, destroy): the OS " + + "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 " diff --git a/docs/developer-guide/Introduction.asciidoc b/docs/developer-guide/Introduction.asciidoc index 5b4da404933..3bed1e9beab 100644 --- a/docs/developer-guide/Introduction.asciidoc +++ b/docs/developer-guide/Introduction.asciidoc @@ -411,9 +411,8 @@ 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. -So the simulator refuses it. A blocking call inside `init`, `start`, `stop` or -`destroy` (and so inside `runApp()` and `onResume(Form)`, which `start()` calls) -throws a `BlockingDisallowedException` that names the callback and fails the run +So the simulator 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 @@ -435,8 +434,8 @@ protected void onReady(boolean firstLaunch) { 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 20 seconds, which keeps a background push -inside the time iOS allows it. To get the old behaviour back, call +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. 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 index 70c649dab09..aa4cde1d3dd 100644 --- a/maven/core-unittests/src/test/java/com/codename1/impl/PushDispatcherTest.java +++ b/maven/core-unittests/src/test/java/com/codename1/impl/PushDispatcherTest.java @@ -25,6 +25,7 @@ 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; @@ -218,4 +219,49 @@ public void run() { }); 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 aDeliveryThatDispatchesAgainRunsInPlace() { + final List log = new ArrayList(); + PushDispatcher.blockingStarted(); + PushDispatcher.dispatch(new Runnable() { + @Override + public void run() { + PushDispatcher.dispatch(record(log, "a-inner")); + log.add("a"); + } + }); + PushDispatcher.dispatch(record(log, "b")); + PushDispatcher.blockingEnded(); + flushSerialCalls(); + assertEquals("[a-inner, a, b]", log.toString()); + } } From 154ee8db9547ea683049c7c39d97900f05e1f57c Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:52:31 +0200 Subject: [PATCH 3/9] PushDispatcher: hold new pushes during a blocked handler; restore only what was there Co-Authored-By: Claude Opus 5.5 --- .../com/codename1/impl/PushDispatcher.java | 34 +++++++++++++------ CodenameOne/src/com/codename1/ui/Display.java | 3 ++ .../codename1/impl/PushDispatcherTest.java | 21 ++++++++++++ 3 files changed, 48 insertions(+), 10 deletions(-) diff --git a/CodenameOne/src/com/codename1/impl/PushDispatcher.java b/CodenameOne/src/com/codename1/impl/PushDispatcher.java index 9cb7e72fcd7..0b496d4469c 100644 --- a/CodenameOne/src/com/codename1/impl/PushDispatcher.java +++ b/CodenameOne/src/com/codename1/impl/PushDispatcher.java @@ -44,9 +44,12 @@ /// 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): 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. +/// 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)`. /// @@ -57,7 +60,8 @@ public final class PushDispatcher { private static final ArrayList HELD = new ArrayList(); private static int blockingDepth; - private static int delivering; + /// 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; @@ -117,8 +121,11 @@ public void run() { return; } // A delivery that dispatches again (a port path that ends in the generic pushReceived) - // is the same push: run it in place rather than queue it behind later ones. - if (delivering > 0 || !deferred || (blockingDepth == 0 && HELD.isEmpty())) { + // is the same push: run it in place rather than queue it behind later ones. Only at the + // depth the delivery started at -- a NEW push reaching the EDT while that delivery is + // blocked (its handler showing a modal Dialog) is deeper, and is held like any other. + boolean reentrant = deliveryDepth >= 0 && deliveryDepth == blockingDepth; + if (reentrant || !deferred || (blockingDepth == 0 && HELD.isEmpty())) { run(delivery); return; } @@ -145,11 +152,12 @@ public static void blockingEnded() { } private static void run(Runnable delivery) { - delivering++; + int saved = deliveryDepth; + deliveryDepth = blockingDepth; try { delivery.run(); } finally { - delivering--; + deliveryDepth = saved; } } @@ -168,8 +176,12 @@ public void run() { }; } + /// Puts back only what the snapshot had, so a held push looks the same to the application as + /// one delivered at once: no type or pushType written where there was none. private static void restore(PushContent c, String pushType) { - Display.getInstance().setProperty("pushType", pushType); + if (pushType != null) { + Display.getInstance().setProperty("pushType", pushType); + } PushContent.reset(); if (c == null) { return; @@ -182,7 +194,9 @@ private static void restore(PushContent c, String pushType) { PushContent.setActionId(c.getActionId()); PushContent.setActionTitle(c.getActionTitle()); PushContent.setTextResponse(c.getTextResponse()); - PushContent.setType(c.getType()); + if (c.getType() != 0) { + PushContent.setType(c.getType()); + } } private static void armHoldLimit(Display d) { diff --git a/CodenameOne/src/com/codename1/ui/Display.java b/CodenameOne/src/com/codename1/ui/Display.java index 6b47990f354..8fa33541530 100644 --- a/CodenameOne/src/com/codename1/ui/Display.java +++ b/CodenameOne/src/com/codename1/ui/Display.java @@ -1372,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(); } 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 index aa4cde1d3dd..b72e161bde0 100644 --- a/maven/core-unittests/src/test/java/com/codename1/impl/PushDispatcherTest.java +++ b/maven/core-unittests/src/test/java/com/codename1/impl/PushDispatcherTest.java @@ -264,4 +264,25 @@ public void run() { flushSerialCalls(); assertEquals("[a-inner, a, b]", log.toString()); } + + @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()); + } } From f6184b7ff440bf7f8b8b053fba06e6f3ce0cc382 Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:23:56 +0200 Subject: [PATCH 4/9] PushDispatcher: pushes arriving during a delivery wait for it; static gates Co-Authored-By: Claude Opus 5.5 --- .../impl/CodenameOneImplementation.java | 30 ++++++++--- .../com/codename1/impl/PushDispatcher.java | 50 ++++++++++++------- maven/core-unittests/spotbugs-exclude.xml | 8 +++ .../codename1/impl/PushDispatcherTest.java | 26 ++++++++-- 4 files changed, 85 insertions(+), 29 deletions(-) diff --git a/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java b/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java index 8aa9b38af77..76dbd909a83 100644 --- a/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java +++ b/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java @@ -11081,17 +11081,33 @@ protected final void sendRegisteredForPush(String id) { } } + /// 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. Inline when already inside a delivery. + // blocking call is in progress. Inside a delivery (a port path that ends here) + // it is the same push, so deliver it in place. final PushCallback c = callback; - PushDispatcher.dispatch(new Runnable() { - @Override - public void run() { - c.push(data); - } - }); + if (PushDispatcher.isDelivering()) { + c.push(data); + return; + } + PushDispatcher.dispatch(new PushDelivery(c, data)); } } diff --git a/CodenameOne/src/com/codename1/impl/PushDispatcher.java b/CodenameOne/src/com/codename1/impl/PushDispatcher.java index 0b496d4469c..23d63a0b180 100644 --- a/CodenameOne/src/com/codename1/impl/PushDispatcher.java +++ b/CodenameOne/src/com/codename1/impl/PushDispatcher.java @@ -75,9 +75,10 @@ public final class PushDispatcher { 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 token it was armed - /// with and does nothing unless it is still the current one. - private static Object holdToken; + /// 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() { @@ -120,12 +121,11 @@ public void run() { }); return; } - // A delivery that dispatches again (a port path that ends in the generic pushReceived) - // is the same push: run it in place rather than queue it behind later ones. Only at the - // depth the delivery started at -- a NEW push reaching the EDT while that delivery is - // blocked (its handler showing a modal Dialog) is deeper, and is held like any other. - boolean reentrant = deliveryDepth >= 0 && deliveryDepth == blockingDepth; - if (reentrant || !deferred || (blockingDepth == 0 && HELD.isEmpty())) { + // 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; } @@ -158,9 +158,20 @@ private static void run(Runnable delivery) { 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) { @@ -200,15 +211,15 @@ private static void restore(PushContent c, String pushType) { } private static void armHoldLimit(Display d) { - if (holdToken != null) { + if (holdArmed) { return; } - final Object token = new Object(); - holdToken = token; + holdArmed = true; + final int generation = ++holdGeneration; holdTimer = d.setTimeout(holdLimitMs, new Runnable() { @Override public void run() { - if (holdToken != token) { + if (!holdArmed || holdGeneration != generation) { return; } endHoldLimit(); @@ -220,10 +231,11 @@ public void run() { /// 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() { - holdToken = null; - if (holdTimer != null) { - holdTimer.cancel(); - holdTimer = null; + holdArmed = false; + Timer t = holdTimer; + holdTimer = null; + if (t != null) { + t.cancel(); } } @@ -258,7 +270,9 @@ private static void deliverHeldNow() { 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. - while (!HELD.isEmpty() && (force || blockingDepth == 0 || !deferred)) { + // 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 { 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 index b72e161bde0..7b4fbe20432 100644 --- a/maven/core-unittests/src/test/java/com/codename1/impl/PushDispatcherTest.java +++ b/maven/core-unittests/src/test/java/com/codename1/impl/PushDispatcherTest.java @@ -249,20 +249,38 @@ public void run() { } @FormTest - void aDeliveryThatDispatchesAgainRunsInPlace() { + 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, "a-inner")); + PushDispatcher.dispatch(record(log, "b")); log.add("a"); } }); - PushDispatcher.dispatch(record(log, "b")); + PushDispatcher.dispatch(record(log, "c")); PushDispatcher.blockingEnded(); flushSerialCalls(); - assertEquals("[a-inner, a, b]", log.toString()); + 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 From 44782da71cf85dd2c76f9484d7a5850dc970eaec Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:30:24 +0200 Subject: [PATCH 5/9] PushDispatcher: EDT-only in-place delivery, held pushType restored exactly Co-Authored-By: Claude Opus 5.5 --- .../com/codename1/impl/CodenameOneImplementation.java | 7 +++++-- CodenameOne/src/com/codename1/impl/PushDispatcher.java | 10 +++++----- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java b/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java index 76dbd909a83..341d886bfed 100644 --- a/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java +++ b/CodenameOne/src/com/codename1/impl/CodenameOneImplementation.java @@ -11101,9 +11101,12 @@ 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. + // 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 (PushDispatcher.isDelivering()) { + if (Display.getInstance().isEdt() && PushDispatcher.isDelivering()) { c.push(data); return; } diff --git a/CodenameOne/src/com/codename1/impl/PushDispatcher.java b/CodenameOne/src/com/codename1/impl/PushDispatcher.java index 23d63a0b180..e9b879d3546 100644 --- a/CodenameOne/src/com/codename1/impl/PushDispatcher.java +++ b/CodenameOne/src/com/codename1/impl/PushDispatcher.java @@ -187,12 +187,12 @@ public void run() { }; } - /// Puts back only what the snapshot had, so a held push looks the same to the application as - /// one delivered at once: no type or pushType written where there was none. + /// 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) { - if (pushType != null) { - Display.getInstance().setProperty("pushType", 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; From f78b38a435f7e0e6e87e3938894d12f333b6e969 Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:15:59 +0200 Subject: [PATCH 6/9] Docs: make the onReady and horizontal ActivityTimeline snippets self-contained Co-Authored-By: Claude Opus 5.5 --- .../developerguide/snippets/InputAndProgressSnippets.java | 4 +++- docs/developer-guide/Introduction.asciidoc | 7 ++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/InputAndProgressSnippets.java b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/InputAndProgressSnippets.java index b75ba8c8f4d..84b2496e9c2 100644 --- a/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/InputAndProgressSnippets.java +++ b/docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/InputAndProgressSnippets.java @@ -179,7 +179,9 @@ public void activityTimeline() { .addStep("Shipping", null, null, ActivityTimeline.CURRENT) .addStep("Payment", null, null, ActivityTimeline.PENDING) .addStep("Review", null, null, ActivityTimeline.PENDING); - form.add(checkout); + Form wizard = new Form("Checkout", BoxLayout.y()); + wizard.add(checkout); + wizard.show(); // end::activity-timeline-horizontal[] } diff --git a/docs/developer-guide/Introduction.asciidoc b/docs/developer-guide/Introduction.asciidoc index 3bed1e9beab..96f9dbe7518 100644 --- a/docs/developer-guide/Introduction.asciidoc +++ b/docs/developer-guide/Introduction.asciidoc @@ -421,12 +421,13 @@ every resume (`false`). Blocking there is fine: [source,java] ---- -@Override +// in your Lifecycle subclass protected void onReady(boolean firstLaunch) { - if (!firstLaunch && sessionExpired()) { + 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); - new LoginForm().show(); } } ---- From 2a8cf6b6dee6bb99489f48c1299e1f5f144a1417 Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:35:29 +0200 Subject: [PATCH 7/9] Docs: onReady example moves to docs/demos and is included by tag Co-Authored-By: Claude Opus 5.5 --- .../snippets/LifecycleOnReadySnippet.java | 44 +++++++++++++++++++ docs/developer-guide/Introduction.asciidoc | 10 +---- 2 files changed, 45 insertions(+), 9 deletions(-) create mode 100644 docs/demos/common/src/main/java/com/codenameone/developerguide/snippets/LifecycleOnReadySnippet.java 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 96f9dbe7518..5e3b2a2d7dc 100644 --- a/docs/developer-guide/Introduction.asciidoc +++ b/docs/developer-guide/Introduction.asciidoc @@ -421,15 +421,7 @@ every resume (`false`). Blocking there is fine: [source,java] ---- -// in your Lifecycle subclass -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); - } -} +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 From 592e34d1b9a75eec6deed0fdd71e5010e3ee0a79 Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Tue, 1 Dec 2026 04:08:30 +0200 Subject: [PATCH 8/9] Docs: prose gate fixes in Introduction and Backend-Security Co-Authored-By: Claude Opus 5.5 --- docs/developer-guide/Backend-Security.asciidoc | 2 +- docs/developer-guide/Introduction.asciidoc | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/developer-guide/Backend-Security.asciidoc b/docs/developer-guide/Backend-Security.asciidoc index 5ef2824b435..2975dcf7942 100644 --- a/docs/developer-guide/Backend-Security.asciidoc +++ b/docs/developer-guide/Backend-Security.asciidoc @@ -256,7 +256,7 @@ with no way of signing in answers 403. A signed-in caller that's denied gets a Spring Boot's default error body, `{"timestamp":"...","status":401,"error":"Unauthorized","path":"/api/me"}`, so a client that reads the error body learns why it was refused. Spring's entry point -sends no body at all; a Codename One client's `RequestBuilder` needs one to report +sends an empty response body; a Codename One client's `RequestBuilder` needs one to report the error. [source,java,role=cn1-no-try] diff --git a/docs/developer-guide/Introduction.asciidoc b/docs/developer-guide/Introduction.asciidoc index 5e3b2a2d7dc..b6374a1cdb6 100644 --- a/docs/developer-guide/Introduction.asciidoc +++ b/docs/developer-guide/Introduction.asciidoc @@ -401,7 +401,7 @@ survives the app being killed while suspended. [[LifecycleNoBlocking]] ===== Never block inside a lifecycle callback -`start()` is not only the app launching. On a phone the OS calls it whenever the +`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 @@ -411,7 +411,7 @@ 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. -So the simulator refuses it. A blocking call inside `init` or `start` (and so +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. From 72c95d6a45b9b9d2ccec9120098f702ee327d18a Mon Sep 17 00:00:00 2001 From: Shai Almog <67850168+shai-almog@users.noreply.github.com> Date: Tue, 1 Dec 2026 05:42:24 +0200 Subject: [PATCH 9/9] Docs: quote Design Import screenshot alt text that contains commas Co-Authored-By: Claude Opus 5.5 --- docs/developer-guide/Design-Import.asciidoc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/developer-guide/Design-Import.asciidoc b/docs/developer-guide/Design-Import.asciidoc index 1f807a91adb..607e21c7640 100644 --- a/docs/developer-guide/Design-Import.asciidoc +++ b/docs/developer-guide/Design-Import.asciidoc @@ -14,7 +14,7 @@ things: The tool doesn't pretend the result is finished. Every guess it makes and every effect that CSS can't express is recorded as an issue, with the layer it applies to and how to fix it. -image::img/design-import/workbench.png[The review step: layers on the left, the design and the live form side by side, the selected text field outlined in both, the issue guide and the inspector on the right,role="text-center"] +image::img/design-import/workbench.png["The review step: layers on the left, the design and the live form side by side, the selected text field outlined in both, the issue guide and the inspector on the right",role="text-center"] === Importing a design into your project @@ -36,7 +36,7 @@ This opens the import wizard. It takes four steps: . *Write*: confirm the package, and the forms go into the project, each named after its screen. -image::img/design-import/wizard.png[The wizard's screens step: a card for each screen of the design with its thumbnail, all of them chosen,role="text-center"] +image::img/design-import/wizard.png["The wizard's screens step: a card for each screen of the design with its thumbnail, all of them chosen",role="text-center"] The screens shown here and below come from the Laza E-commerce UI Kit, a Figma Community file published under CC BY 4.0. @@ -49,7 +49,7 @@ what it's for. Press *?* in the title bar to play the tour of the step you're on through it and *Skip* to close it. The review step's tour plays by itself the first time you reach it. -image::img/design-import/tour.png[The review step's tour: the design pane is outlined and a bubble explains it, with Skip and Next buttons and a step count,role="text-center"] +image::img/design-import/tour.png["The review step's tour: the design pane is outlined and a bubble explains it, with Skip and Next buttons and a step count",role="text-center"] Name the design to skip the window and import it as it comes: