public final class Display
- Object
- CN1Constants
- Display
Central class for the API that manages rendering/events and is used to place top
level components (Form) on the “display”.
This class handles the main thread for the toolkit referenced here on as the EDT (Event Dispatch Thread) similar to the Swing EDT. This thread encapsulates the platform specific event delivery and painting semantics and enables threading features such as animations etc…
The EDT should not be blocked since paint operations and events would also be blocked
in much the same way as they would be in other platforms. To serialize calls back
into the EDT, use the methods Display#callSerially & Display#callSeriallyAndWait.
Notice that all Codename One calls occur on the EDT (events, painting, animations, etc…), Codename One
should normally be manipulated on the EDT as well (hence the Display#callSerially &
Display#callSeriallyAndWait methods). Theoretically, it should be possible to manipulate
some Codename One features from other threads, but this can’t be guaranteed to work for all use cases.
Fields
public static final String SOUND_TYPE_ALARM = "alarm" | A common sound type that can be used with playBuiltinSound |
public static final String SOUND_TYPE_CONFIRMATION = "confirmation" | A common sound type that can be used with playBuiltinSound |
public static final String SOUND_TYPE_ERROR = "error" | A common sound type that can be used with playBuiltinSound |
public static final String SOUND_TYPE_INFO = "info" | A common sound type that can be used with playBuiltinSound |
public static final String SOUND_TYPE_WARNING = "warning" | A common sound type that can be used with playBuiltinSound |
public static final String SOUND_TYPE_BUTTON_PRESS = "press" | A common sound type that can be used with playBuiltinSound |
public static final int KEYBOARD_TYPE_UNKNOWN = 0 | Unknown keyboard type is the default indicating the software should try to detect the keyboard type if necessary |
public static final int KEYBOARD_TYPE_NUMERIC = 1 | Numeric keypad keyboard type |
public static final int KEYBOARD_TYPE_QWERTY = 2 | Full QWERTY keypad keyboard type, even if a numeric keyboard also exists |
public static final int KEYBOARD_TYPE_VIRTUAL = 3 | A touch based device that doesn’t have a physical keyboard. |
public static final int KEYBOARD_TYPE_HALF_QWERTY = 4 | Half-QWERTY which needs software assistance for completion |
public static final int GAME_FIRE = 8 | Game action for fire |
public static final int GAME_LEFT = 2 | Game action for the left key |
public static final int GAME_RIGHT = 5 | Game action for right key |
public static final int GAME_UP = 1 | Game action for UP key |
public static final int GAME_DOWN = 6 | Game action for down key |
public static final int MEDIA_KEY_SKIP_FORWARD = 20 | Special case game key used for media playback events |
public static final int MEDIA_KEY_SKIP_BACK = 21 | Special case game key used for media playback events |
public static final int MEDIA_KEY_PLAY = 22 | Special case game key used for media playback events |
public static final int MEDIA_KEY_STOP = 23 | Special case game key used for media playback events |
public static final int MEDIA_KEY_PLAY_STOP = 24 | Special case game key used for media playback events |
public static final int MEDIA_KEY_PLAY_PAUSE = 25 | Special case game key used for media playback events |
public static final int MEDIA_KEY_FAST_FORWARD = 26 | Special case game key used for media playback events |
public static final int MEDIA_KEY_FAST_BACKWARD = 27 | Special case game key used for media playback events |
public static final int KEY_POUND = 35 | An attribute that encapsulates ‘#’ int value. |
public static final int SHOW_DURING_EDIT_IGNORE = 1 | Ignore all calls to show occurring during edit, they are discarded immediately |
public static final int SHOW_DURING_EDIT_EXCEPTION = 2 | If show is called while editing text in the native text box an exception is thrown |
public static final int SHOW_DURING_EDIT_ALLOW_DISCARD = 3 | Allow show to occur during edit and discard all user input at this moment |
public static final int SHOW_DURING_EDIT_ALLOW_SAVE = 4 | Allow show to occur during edit and save all user input at this moment |
public static final int SHOW_DURING_EDIT_SET_AS_NEXT = 5 | Show will update the current form to which the OK button of the text box will return |
public static final int COMMAND_BEHAVIOR_DEFAULT = 1 | Indicates that the Codename One implementation should decide internally the command behavior most appropriate for this platform. |
public static final int COMMAND_BEHAVIOR_SOFTKEY = 2 | Indicates the classic Codename One command behavior where the commands are placed in a list within a dialog. |
public static final int COMMAND_BEHAVIOR_TOUCH_MENU = 3 | Indicates the touch menu dialog rendered by Codename One where commands are placed into a scrollable dialog |
public static final int COMMAND_BEHAVIOR_BUTTON_BAR = 4 | Indicates that commands should be added to an always visible bar at the bottom of the form. |
public static final int COMMAND_BEHAVIOR_BUTTON_BAR_TITLE_BACK = 5 | Identical to the bar behavior, places the back command within the title bar of the form/dialg |
public static final int COMMAND_BEHAVIOR_BUTTON_BAR_TITLE_RIGHT = 6 | Places all commands on the right side of the title bar with a uniform size grid layout |
public static final int COMMAND_BEHAVIOR_ICS = 7 | Commands are placed in the same was as they are in the ice cream sandwich Android OS update where the back button has a theme icon the application icon appears next to the |
public static final int COMMAND_BEHAVIOR_SIDE_NAVIGATION = 8 | Commands are placed in a side menu similar to Facebook/Google+ apps |
public static final int COMMAND_BEHAVIOR_NATIVE = 10 | Indicates that commands should try to add themselves to the native menus |
public static final String WINDOW_SIZE_HINT_PERCENT = "cn1.windowSizePercent" | Client property key used on the first shown Form to indicate the desired initial window size as a percentage of the available desktop. |
Methods
public static void init(Object m) | |
public static void deinitialize() | Closes down the EDT and Codename One, under normal conditions this method is completely unnecessary since exiting the application will shut down Codename One. |
public static boolean isInitialized() | This method returns true if the Display is initialized. |
public static Display getInstance() | Return the Display instance |
public void setBookmark(Runnable bookmark) | Sets a bookmark that can restore the app to a particular state. |
public void restoreToBookmark() | Runs the last bookmark that was set using #setBookmark(java.lang.Runnable) |
public PluginSupport getPluginSupport() | Gets reference to plugin support object. |
public int getDragStartPercentage() | This method allows us to manipulate the drag started detection logic. |
public void setDragStartPercentage(int dragStartPercentage) | This method allows us to manipulate the drag started detection logic. |
public WifiPlatform getWifiPlatform() | Returns the platform’s WiFi implementation. |
public WifiDirectPlatform getWifiDirectPlatform() | Returns the platform’s WiFi-Direct implementation. |
public BonjourPlatform getBonjourPlatform() | Returns the platform’s Bonjour / mDNS implementation. |
public UsbPlatform getUsbPlatform() | Returns the platform’s USB host implementation. |
public NetworkTypePlatform getNetworkTypePlatform() | Returns the platform’s network-type tracker used by NetworkManager.addNetworkTypeListener(...). |
public Simd getSimd() | Returns the SIMD API instance bound to the current implementation. |
public boolean isGpuSupported() | Returns true if the current platform provides a hardware accelerated 3D GPU backend for com.codename1.gpu.RenderView. |
public PeerComponent createGpuPeer(RenderView view) | Creates the native GPU peer backing a RenderView. |
public void gpuSetContinuous(PeerComponent peer, boolean continuous) | Sets whether a GPU peer renders continuously or only on demand. |
public void gpuRequestRender(PeerComponent peer) | Requests a single frame from a GPU peer. |
public void setFramerate(int rate) | Indicates the maximum frames the API will try to draw every second by default this is set to 10. |
public void vibrate(int duration) | Vibrates the device for the given length of time, notice that this might ignore the time value completely on some OS’s where this level of control isn’t supported e.g. iOS see: https://github.com/codenameone/CodenameOne/issues/1904 |
public void flashBacklight(int duration) | Deprecated Flash the backlight of the device for the given length of time |
public void announceForAccessibility(Component cmp, String text) | Manually announces text to native accessibility services, optionally associating the announcement with a specific component. |
public void announceForAccessibility(String text) | Convenience overload to announce text without specifying a component. |
public void accessibilityTreeChanged(int changeType) | Notifies the native port that the portable semantic tree changed. |
public void accessibilityTreeChanged(int changeType, int windowId) | Notifies the native port that one surface’s semantic tree changed. |
public boolean isAccessibilityTreeSupported() | Returns true when the active port exposes lightweight components through a native virtual accessibility tree. |
public boolean isAccessibilityTreeUpdateRequired() | Returns true when the active port currently needs semantic changes to be projected eagerly. |
public int getShowDuringEditBehavior() | Deprecated Returns the status of the show during edit flag |
public void setShowDuringEditBehavior(int showDuringEdit) | Deprecated Invoking the show() method of a form/dialog while the user is editing text in the native text box can have several behaviors: SHOW_DURING_EDIT_IGNORE, SHOW_DURING_EDIT_EXCEPTION, SHOW_DURING_EDIT_ALLOW_DISCARD, SHOW_DURING_EDIT_ALLOW_SAVE,… |
public int getFrameRate() | Indicates the maximum frames the API will try to draw every second |
public boolean isEdt() | Returns true if we are currently in the event dispatch thread. |
public void stopRemoteControl() | Stops the remote control service. |
public void startRemoteControl() | Starts the remote control service. |
public Boolean isDarkMode() | Returns true if the platform is in dark mode, null is returned for unknown status |
public void setDarkMode(Boolean darkMode) | Override the default dark mode setting |
public boolean isLargerTextEnabled() | Returns true if the user has selected larger type fonts in the system settings. |
public float getLargerTextScale() | Returns a scale factor representing how much larger system fonts should be. |
public boolean isHighContrastEnabled() | Returns true when the user requests stronger foreground/background contrast. |
public boolean isDifferentiateWithoutColorEnabled() | Returns true when the user requests that information isn’t conveyed by color alone. |
public AccessibilityColorVisionDeficiency getColorVisionDeficiency() | Returns the selected color-vision correction, or AccessibilityColorVisionDeficiency.UNKNOWN when the platform doesn’t expose it. |
public boolean isReduceMotionEnabled() | Returns true when the user requests reduced or disabled nonessential motion. |
public boolean isReduceTransparencyEnabled() | Returns true when the user requests reduced transparency and blur effects. |
public boolean isBoldTextEnabled() | Returns true when the user requests heavier text weight. |
public boolean isInvertColorsEnabled() | Returns true when the operating system is inverting displayed colors. |
public boolean isGrayscaleEnabled() | Returns true when the operating system requests a grayscale presentation. |
public boolean isOnOffSwitchLabelsEnabled() | Returns true when switches should include visible on/off labels. |
public boolean isScreenReaderEnabled() | Returns true when a screen reader or touch-exploration service is active. |
public boolean isEnableAsyncStackTraces() | Checks if async stack traces are enabled. |
public void setEnableAsyncStackTraces(boolean enableAsyncStackTraces) | Enables or disables async stack traces. |
public void callSerially(Runnable r) | Causes the runnable to be invoked on the event dispatch thread. |
public void callSeriallyOnIdle(Runnable r) | Causes the runnable to be invoked on the event dispatch thread when the event dispatch thread is idle. |
public String getLineSeparator() | |
public void scheduleBackgroundTask(Runnable r) | Allows executing a background task in a separate low priority thread. |
public void callSeriallyAndWait(Runnable r) | Identical to callSerially with the added benefit of waiting for the Runnable method to complete. |
public boolean platformUsesInputMode() | Checks if this platform uses input modes. |
public void callSeriallyAndWait(Runnable r, int timeout) | Identical to callSerially with the added benefit of waiting for the Runnable method to complete. |
public boolean isInTransition() | Returns true if the system is currently in the process of transitioning between forms |
public String getStackTrace(Thread parentThread, Throwable t) | Returns the stack trace from the exception on the given thread. |
public void onEditingComplete(Component c, String text) | Called by the underlying implementation to indicate that editing in the native system has completed and changes should propagate into Codename One |
public void invokeWithoutBlocking(Runnable r) | Invokes a Runnable with blocking disabled. |
public <T> T invokeWithoutBlockingWithResultSync(RunnableWithResultSync<T> r) | Invokes a RunnableWithResultSync with blocking disabled. |
public void invokeAndBlock(Runnable r, boolean dropEvents) | Invokes runnable and blocks the current thread, if the current thread is the EDT it will still be blocked in a way that doesn’t break event dispatch . Important: calling this method spawns a new thread that shouldn’t access the UI! |
public void invokeAndBlock(Runnable r) | Invokes runnable and blocks the current thread, if the current thread is the EDT it will still be blocked in a way that doesn’t break event dispatch . Important: calling this method spawns a new thread that shouldn’t access the UI! |
public boolean isTouchScreenDevice() | The name of this method is misleading due to it’s legacy. |
public void setTouchScreenDevice(boolean touchScreen) | Indicates if this is a touch screen device that will return pen events, defaults to true if the device has pen events but can be overriden by the developer. |
public void setNoSleep(boolean noSleep) | Calling this method with noSleep=true will cause the edt to run without sleeping. |
public void setTransitionYield(int transitionD) | Indicates whether a delay should exist between calls to flush graphics during transition. |
public void editString(Component cmp, int maxSize, int constraint, String text) | Fires the native in place text editing logic, normally you wouldn’t invoke this API directly and instead use an API like com.codename1.ui.TextArea#startEditingAsync(), com.codename1.ui.TextArea#startEditing() or com.codename1.ui.Form#setEditOnShow(com.codename1.ui.TextArea). |
public void editString(Component cmp, int maxSize, int constraint, String text, int initiatingKeycode) | Fires the native in place text editing logic, normally you wouldn’t invoke this API directly and instead use an API like com.codename1.ui.TextArea#startEditingAsync(), com.codename1.ui.TextArea#startEditing() or com.codename1.ui.Form#setEditOnShow(com.codename1.ui.TextArea). |
public void stopEditing(Component cmp) | Allows us to stop editString on the given text component |
public void stopEditing(Component cmp, Runnable onFinish) | Allows us to stop editString on the given text component or Form. |
public boolean minimizeApplication() | Minimizes the current application if minimization is supported by the platform (may fail). |
public boolean isMinimized() | Indicates whether an application is minimized |
public void restoreMinimizedApplication() | Restore the minimized application if minimization is supported by the platform |
public boolean isControlKeyDown() | Checks if the control key is currently down. |
public boolean isMetaKeyDown() | Checks if the meta key is currently down. |
public boolean isAltKeyDown() | Checks if the alt key is currently down. |
public boolean isAltGraphKeyDown() | Checks if the altgraph key is currently down. |
public boolean isRightMouseButtonDown() | Checks if the last mouse press was a right click. |
public boolean isShiftKeyDown() | Checks if shift key is currently down. |
public PointerEvent getCurrentPointerEvent() | Returns a snapshot of the rich detail for the pointer event currently being dispatched such as the mouse button, pointer type (finger/mouse/stylus), pressure and stylus tilt. |
public int getPointerButton() | The mouse button associated with the current pointer event, one of the PointerEvent BUTTON_* constants. |
public int getPressedButtonMask() | A bitmask of the mouse buttons currently held down, built from the PointerEvent MASK_* constants. |
public int getPointerType() | The current pointing device type, one of the PointerEvent TYPE_* constants (finger, mouse, stylus or eraser). |
public float getPointerPressure() | The normalized pressure of the current pointer event between 0.0 and 1.0. |
public float getPointerTiltX() | The stylus tilt across the x axis of the current pointer event in degrees, or 0 when not reported. |
public float getPointerTiltY() | The stylus tilt across the y axis of the current pointer event in degrees, or 0 when not reported. |
public float getPointerContactSize() | The normalized contact size of the current pointer event between 0.0 and 1.0, or 0 when not reported. |
public boolean isStylusPointer() | True if the current pointer is a stylus or pen (Apple Pencil, S-Pen and similar). |
public boolean fireMouseWheelEvent(int x, int y, int scrollX, int scrollY, boolean precise, int modifiers) | Dispatches a mouse wheel event to the component under the given coordinates, and scrolls it. |
public void fireMagnifyGesture(int x, int y, float scale) | Dispatches a magnify (pinch) gesture to the component under the given coordinates, walking up the hierarchy until a component handles it. |
public void fireRotationGesture(int x, int y, float radians) | Dispatches a rotation (twist) gesture to the component under the given coordinates, walking up the hierarchy until a component handles it. |
public void keyPressed(int keyCode) | Pushes a key press event with the given keycode into Codename One |
public void keyReleased(int keyCode) | Pushes a key release event with the given keycode into Codename One |
public void pointerDragged(int[] x, int[] y) | Pushes a pointer drag event with the given coordinates into Codename One |
public void pointerHover(int[] x, int[] y) | Pushes a pointer hover event with the given coordinates into Codename One |
public void pointerHoverPressed(int[] x, int[] y) | Pushes a pointer hover release event with the given coordinates into Codename One |
public void pointerHoverReleased(int[] x, int[] y) | Pushes a pointer hover release event with the given coordinates into Codename One |
public void pointerPressed(int[] x, int[] y) | Pushes a pointer press event with the given coordinates into Codename One |
public void pointerReleased(int[] x, int[] y) | Pushes a pointer release event with the given coordinates into Codename One |
public void sizeChanged(int w, int h) | Notifies Codename One of display size changes, this method is invoked by the implementation class and is for internal use |
public void hideNotify() | Broadcasts hide notify into Codename One, this method is invoked by the Codename One implementation to notify Codename One of hideNotify events |
public void showNotify() | Broadcasts show notify into Codename One, this method is invoked by the Codename One implementation to notify Codename One of showNotify events |
public boolean hasDragOccured() | This method should be invoked by components that broadcast events on the pointerReleased callback. |
public TopLevelContainer getCurrentTopLevel() | Return the form currently displayed on the screen or null if no form is currently displayed. |
public Form getCurrent() | The form currently displayed on the main surface. |
public int numAlphaLevels() | Deprecated Return the number of alpha levels supported by the implementation. |
public int numColors() | Deprecated Returns the number of colors applicable on the device, note that the API does not support gray scale devices. |
public int getDisplayWidth() | Return the width of the display |
public int getDisplayHeight() | Return the height of the display |
public Dimension getDesktopSize() | Returns the size of the desktop hosting the application window when running on a desktop platform. |
public Rectangle getWindowBounds() | Returns the current window bounds when running on a desktop platform. |
public void setWindowSize(int width, int height) | Requests a resize of the application window when supported by the platform. |
public Dimension getInitialWindowSizeHintPercent() | Returns the initial desktop window size hint provided by the first shown form, when available. |
public void setInitialWindowSizeHintPercent(Dimension hint) | Sets the initial desktop window size hint (percent of the desktop) that should be used when the first form is shown. |
public int convertToPixels(int dipCount, boolean horizontal) | Converts the dips count to pixels, dips are roughly 1mm in length. |
public int convertToPixels(float value, byte unitType) | Converts from specified unit to pixels. |
public int convertToPixels(float value, byte unitType, boolean horizontal) | Converts from specified unit to pixels. |
public int convertToPixels(float dipCount) | Converts the dips count to pixels, dips are roughly 1mm in length. |
public int getGameAction(int keyCode) | Returns the game action code matching the given key combination |
public int getKeyCode(int gameAction) | Deprecated Returns the keycode matching the given game action constant (the opposite of getGameAction). |
public boolean isThirdSoftButton() | Indicates whether the 3rd softbutton should be supported on this device |
public void setThirdSoftButton(boolean thirdSoftButton) | Indicates whether the 3rd softbutton should be supported on this device |
public void setShowVirtualKeyboard(boolean show) | Deprecated Displays the virtual keyboard on devices that support manually poping up the vitual keyboard |
public boolean isVirtualKeyboardShowing() | Deprecated Indicates if the virtual keyboard is currently showing or not |
public String[] getSupportedVirtualKeyboard() | Deprecated Returns all platform supported virtual keyboards names |
public void registerVirtualKeyboard(VirtualKeyboardInterface vkb) | Deprecated Register a virtual keyboard |
public VirtualKeyboardInterface getDefaultVirtualKeyboard() | Deprecated Get the default virtual keyboard or null if the VirtualKeyboard is disabled |
public void setDefaultVirtualKeyboard(VirtualKeyboardInterface vkb) | Deprecated Sets the default virtual keyboard to be used by the platform |
public ActionListener getVirtualKeyboardListener() | Deprecated Gets the VirtualKeyboardListener Objects of exists. |
public void setVirtualKeyboardListener(ActionListener l) | Deprecated Sets a listener for VirtualKeyboard hide/show events. |
public void addVirtualKeyboardListener(ActionListener l) | Adds a listener for VirtualKeyboard hide/show events. |
public void removeVirtualKeyboardListener(ActionListener l) | Removes a listener for VirtualKeyboard hide/show events. |
public void fireVirtualKeyboardEvent(boolean show) | Fires a virtual keyboard show event. |
public int getInvisibleAreaUnderVKB() | Gets the invisible area under the Virtual Keyboard. |
public int getKeyboardType() | Returns the type of the input device one of: KEYBOARD_TYPE_UNKNOWN, KEYBOARD_TYPE_NUMERIC, KEYBOARD_TYPE_QWERTY, KEYBOARD_TYPE_VIRTUAL, KEYBOARD_TYPE_HALF_QWERTY |
public boolean isNativeInputSupported() | Indicates whether the device supports native in place editing in which case lightweight input logic shouldn’t be used for input. |
public boolean isMultiTouch() | Indicates whether the device supports multi-touch events, this is only relevant when touch events are supported |
public boolean isClickTouchScreen() | Indicates whether the device has a double layer screen thus allowing two stages to touch events: click and hover. |
public float getDragSpeed(boolean yAxis) | This method returns the dragging speed based on the latest dragged events |
public boolean isBidiAlgorithm() | Indicates whether Codename One should consider the bidi RTL algorithm when drawing text or navigating with the text field cursor. |
public void setBidiAlgorithm(boolean activate) | Indicates whether Codename One should consider the bidi RTL algorithm when drawing text or navigating with the text field cursor. |
public String convertBidiLogicalToVisual(String s) | Converts the given string from logical bidi layout to visual bidi layout so it can be rendered properly on the screen. |
public int getCharLocation(String source, int index) | Returns the index of the given char within the source string, the actual index isn’t necessarily the same when bidi is involved See this for more on visual vs. logical ordering. |
public boolean isRTL(char c) | Returns true if the given character is an RTL character |
public InputStream getResourceAsStream(Class cls, String resource) | This method is essentially equivalent to cls.getResourceAsStream(String) however some platforms might define unique ways in which to load resources within the implementation. |
public void addEdtErrorHandler(ActionListener e) | An error handler will receive an action event with the source exception from the EDT once an error handler is installed the default Codename One error dialog will no longer appear |
public String getNativeLogSnapshot() | An error handler will receive an action event with the source exception from the EDT once an error handler is installed the default Codename One error dialog will no longer appear |
public void installNativeCrashHandler() | Installs the platform native crash handler used by crash protection. |
public String consumePendingNativeCrash() | Returns the captured native crash evidence (raw backtrace + signal info as a text blob) from installNativeCrashHandler(), or null if none. |
public void removeEdtErrorHandler(ActionListener e) | |
public boolean isAllowMinimizing() | Allows a Codename One application to minimize without forcing it to the front whenever a new dialog is poped up |
public void setAllowMinimizing(boolean allowMinimizing) | Allows a Codename One application to minimize without forcing it to the front whenever a new dialog is poped up |
public boolean shouldRenderSelection() | This is an internal state flag relevant only for pureTouch mode (otherwise it will always be true). |
public boolean shouldRenderSelection(Component c) | |
public boolean isPureTouch() | A pure touch device has no focus showing when the user is using the touch interface. |
public void setPureTouch(boolean pureTouch) | A pure touch device has no focus showing when the user is using the touch interface. |
public boolean isNativeCommands() | Deprecated Indicates whether Codename One commands should be mapped to the native menus |
public void setNativeCommands(boolean nativeCommands) | Deprecated Indicates whether Codename One commands should be mapped to the native menus |
public void exitApplication() | Exits the application… |
public void exitAndClearTask() | Exits the application and removes it from the platform’s list of recent tasks, so the user cannot bring it back by picking it out of the task switcher. |
public boolean isExitAndClearTaskSupported() | Indicates whether this platform can remove the application from its list of recent tasks on exit. |
public boolean isFullScreenSupported() | Checks if this platform supports full-screen mode. |
public boolean requestFullScreen() | Try to enter full-screen mode if the platform supports it. |
public boolean exitFullScreen() | Try to exit full-screen mode if the platform supports it. |
public boolean isInFullScreenMode() | Checks if the app is currently running in full-screen mode. |
public void showNativeScreen(Object nativeFullScreenPeer) | Shows a native Form/Canvas or some other heavyweight native screen |
public boolean isAutoFoldVKBOnFormSwitch() | Normally Codename One folds the VKB when switching forms this field allows us to block that behavior. |
public void setAutoFoldVKBOnFormSwitch(boolean autoFoldVKBOnFormSwitch) | Normally Codename One folds the VKB when switching forms this field allows us to block that behavior. |
public int getCommandBehavior() | Deprecated Indicates the way commands should be added to a form as one of the ocmmand constants defined in this class |
public void setCommandBehavior(int commandBehavior) | Deprecated Indicates the way commands should be added to a form as one of the ocmmand constants defined in this class |
public void postMessage(MessageEvent message) | Posts a message to the native platform. |
public void addMessageListener(ActionListener<MessageEvent> l) | Adds a listener to receive messages from the native platform. |
public void removeMessageListener(ActionListener<MessageEvent> l) | Removes a listener from receiving messages from the native platform. |
public void dispatchMessage(MessageEvent evt) | Dispatches a message to all of the registered listeners. |
public void addWindowListener(ActionListener<WindowEvent> l) | Adds a listener to receive notifications about native window changes such as resize or movement. |
public void removeWindowListener(ActionListener<WindowEvent> l) | Removes a previously registered window listener. |
public void fireWindowEvent(WindowEvent evt) | Dispatches a window change event to registered listeners. |
public String getProperty(String key, String defaultValue) | Returns the property from the underlying platform deployment or the default value if no deployment values are supported. |
public boolean isApnsPushDevice() | Whether this port’s device subscribes to push through APNs. |
public boolean isNativeRedirects() | Whether this port follows HTTP redirects below the portable network layer, so the framework cannot see where a download actually came from. |
public void setProperty(String key, String value) | Sets a local property to the application, this method has no effect on the implementation code and only allows the user to override the logic of getProperty for internal application purposes. |
public Boolean canExecute(String url) | Returns true if executing this URL should work, returns false if it will not and null if this is unknown. |
public void execute(String url) | Executes the given URL on the native platform. |
public void execute(String url, ActionListener response) | Executes the given URL on the native platform, this method is useful if the platform has the ability to send an event to the app when the execution has ended, currently this works only for Android platform to invoke other intents. |
public boolean downloadBytesAsFile(String fileName, byte[] bytes) | Offers the given in-memory bytes to the user as a downloadable file, bypassing local storage. |
public int getDeviceDensity() | Returns one of the density variables appropriate for this device, notice that density doesn’t always correspond to resolution and an implementation might decide to change the density based on DPI constraints. |
public float getDevicePixelRatio() | The platform’s logical-pixel scale factor – device pixels per logical pixel, what iOS calls UIScreen.scale and Android calls density. |
public boolean isRoundedImageSupported() | Whether this platform can round a picture’s corners as it draws it, rather than the caller having to build a rounded copy of the bitmap. |
public String getDensityStr() | Returns the device density as a string. |
public void playBuiltinSound(String soundIdentifier) | Deprecated Plays a builtin device sound matching the given identifier, implementations and themes can offer additional identifiers to the ones that are already built in. |
public Rectangle getDisplaySafeArea(Rectangle rect) | Gets the display safe area as a rectangle. |
public void installBuiltinSound(String soundIdentifier, InputStream data)
throws IOException | Installs a replacement sound as the builtin sound responsible for the given sound identifier (this will override the system sound if such a sound exists). |
public boolean isBuiltinSoundAvailable(String soundIdentifier) | Deprecated Indicates whether a user installed or system sound is available |
public boolean isBuiltinSoundsEnabled() | Allows muting/unmuting the builtin sounds easily |
public void setBuiltinSoundsEnabled(boolean enabled) | Allows muting/unmuting the builtin sounds easily |
public Media createMedia(String uri, boolean isVideo, Runnable onCompletion)
throws IOException | Creates a sound in the given URI which is partially platform specific. |
public AsyncResource<Media> createMediaAsync(String uri, boolean video, Runnable onCompletion) | Creates media asynchronously. |
public void addCompletionHandler(Media media, Runnable onCompletion) | Adds a callback to a Media element that will be called when the media finishes playing. |
public void removeCompletionHandler(Media media, Runnable onCompletion) | Removes onComplete callback from Media element. |
public Media createMedia(InputStream stream, String mimeType, Runnable onCompletion)
throws IOException | Create the sound in the given stream Notice that an audio is “auto destroyed” on completion and cannot be played twice! |
public AsyncResource<Media> createMediaAsync(InputStream stream, String mimeType, Runnable onCompletion) | |
public boolean isSoundPoolSupported() | Indicates whether this platform provides a native low latency sound pool backing com.codename1.gaming.SoundPool. |
public SoundPoolPeer createSoundPool(int maxStreams) | Creates a native low latency sound pool peer for com.codename1.gaming.SoundPool, or returns null when this platform has no native backend. |
public Object createSoftWeakRef(Object o) | Creates a soft/weak reference to an object that allows it to be collected yet caches it. |
public Object extractHardRef(Object o) | Extracts the hard reference from the soft/weak reference given |
public boolean hasNativeTheme() | Indicates if the implemenetation has a native underlying theme |
public void installNativeTheme() | Installs the native theme, this is only applicable if hasNativeTheme() returned true. |
public void copyToClipboard(Object obj) | Performs a clipboard copy operation, if the native clipboard is supported by the implementation it would be used |
public void copyToClipboard(ClipboardContent content) | Copies a set of alternative clipboard representations. |
public Object getPasteDataFromClipboard() | Returns the current content of the clipboard |
public ClipboardContent getClipboardContent() | Returns all clipboard representations exposed by the current port, or null if none are available. |
public boolean isPortrait() | Returns true if the device is currently in portrait mode |
public boolean isLockOrientation() | Returns true if orientation was locked using #lockOrientation(boolean) and not yet unlocked via #unlockOrientation(). |
public boolean canForceOrientation() | Returns true if the device allows forcing the orientation via code, feature phones do not allow this although some include a jad property allowing for this feature |
public void lockOrientation(boolean portrait) | On devices that return true for canForceOrientation() this method can lock the device orientation either to portrait or landscape mode |
public void unlockOrientation() | This is the reverse method for lock orientation allowing orientation lock to be disabled |
public boolean isTablet() | Indicates whether the device is a tablet, notice that this is often a guess |
public boolean isDesktop() | Returns true if this is a desktop application |
public boolean isWatch() | Indicates whether the application is running on a smartwatch form factor (Apple Watch / Wear OS). |
public boolean isTV() | Indicates whether the application is running on a television form factor (Apple TV / Android TV / Google TV). |
public boolean isCarConnected() | Indicates whether a head unit (Apple CarPlay / Google Android Auto) is currently connected and projecting the com.codename1.car experience. |
public boolean isFoldable() | True if the device is a foldable or dual screen device such as a Galaxy Fold, Galaxy Flip, Pixel Fold or Surface Duo. |
public DevicePosture getDevicePosture() | Returns the live device fold posture. |
public void addPostureListener(ActionListener l) | Adds a listener that is notified when the device is folded, unfolded or changes posture. |
public void removePostureListener(ActionListener l) | Removes a posture listener. |
public void postureChanged() | Invoked by the implementation when the device fold posture changes. |
public boolean isDesktopMode() | True if the application is currently running in a desktop windowing mode such as Samsung DeX, Android desktop windowing or iPad Stage Manager. |
public int getDisplayCount() | Returns the number of displays (monitors or external screens) currently attached. |
public boolean isExternalDisplayConnected() | True if an external or secondary display is currently attached. |
public CarBridge getCarBridge() | Returns the platform bridge used by the com.codename1.car API to render in-car templates, or null when in-car projection is unsupported on this port. |
public WearableBridge getWearableBridge() | Returns the platform bridge used by the com.codename1.wearable API to talk to the counterpart watch or phone app, or null when this device has no wearable counterpart. |
public HomeBridge getHomeBridge() | Returns the platform bridge used by the com.codename1.home API to reach HomeKit, the Google Home APIs or a local simulated home, or null when this port has no smart-home support. |
public NearbyBridge getNearbyBridge() | Returns the platform bridge used by the com.codename1.nearby API to reach precision ranging, companion-device association and the nearby transport, or null when this port implements none of them. |
public CallBridge getCallBridge() | Returns the platform bridge used by the com.codename1.call API to reach the system call stack – CallKit and PushKit on iOS, ConnectionService and TelecomManager on Android – or null when unsupported on this port. |
public VpnBridge getVpnBridge() | Returns the platform bridge used by the com.codename1.vpn API to manage VPN configurations, or null when unsupported on this port. |
public SurfaceBridge getSurfaceBridge() | Returns the platform bridge used by the com.codename1.surfaces API to render external surfaces (home-screen widgets and live activities), or null when unsupported on this port. |
public DocumentProviderBridge getDocumentProviderBridge() | Returns the platform bridge used by the com.codename1.documents API to expose the application’s documents to the system file browser, or null when unsupported on this port. |
public ContinuityBridge getContinuityBridge() | Returns the platform bridge used by the com.codename1.continuity API to advertise the user’s current activity to their other devices and to reach the platform’s synced key/value store, or null when unsupported on this port. |
public IntentBridge getIntentBridge() | Returns the platform bridge used by the com.codename1.intents API to expose the application’s capabilities to the system, or null when unsupported on this port. |
public boolean canDial() | Returns true if the device has dialing capabilities |
public boolean areMutableImagesFast() | On most platforms it is quite fast to draw on a mutable image and then render that image, however some platforms have much slower mutable images in comparison to just drawing on the screen. |
public LocationManager getLocationManager() | This method returns the platform Location Manager used for geofencing. |
public boolean isLocationButtonSupported() | Whether this platform draws a location button of its own. |
public PeerComponent createLocationButton(int textType, int backgroundColor, int textColor, SuccessCallback<Boolean> onPermissionResult) | Builds the platform’s own location button. |
public boolean isLocationButtonReady(PeerComponent button) | Whether a control from createLocationButton is actually live. |
public MotionSensorManager getMotionSensorManager() | Returns the platform motion sensor entry point or null when the current port does not provide motion sensors. |
public Biometrics getBiometrics() | Returns the platform biometric authentication entry point. |
public SecureStorage getSecureStorage() | Returns the platform biometric-gated secure storage. |
public Nfc getNfc() | Returns the platform NFC entry point. |
public LocalCalendarSource getLocalCalendarSource() | Returns the active port’s local device-calendar source. |
public Bluetooth getBluetooth() | Returns the platform Bluetooth entry point. |
public Health getHealth() | Returns the platform health entry point. |
public void capturePhoto(ActionListener response) | This method tries to invoke the device native camera to capture images. |
public void captureAudio(ActionListener<ActionEvent> response) | This method tries to invoke the device native hardware to capture audio. |
public void captureAudio(MediaRecorderBuilder recordingOptions, ActionListener response) | This method tries to invoke the device native hardware to capture audio. |
public void captureVideo(ActionListener response) | This method tries to invoke the device native camera to capture video. |
public void captureVideo(VideoCaptureConstraints constraints, ActionListener response) | Same as #captureVideo(com.codename1.ui.events.ActionListener), except that it attempts to impose constraints on the capture. |
public void openImageGallery(ActionListener response) | Deprecated Opens the device image gallery The method returns immediately and the response will be sent asynchronously to the given ActionListener Object |
public void openGallery(ActionListener response, int type) | Opens the device gallery to pick an image or a video. |
public void openFileChooser(ActionListener response, String accept) | Opens a file chooser for arbitrary user-selected files. |
public boolean isGalleryTypeSupported(int type) | Checks to see if the given gallery type is supported on the current platform. |
public String getPlatformName() | Returns a 2-3 letter code representing the platform name for the platform override |
public String[] getPlatformOverrides() | Returns the suffixes for ovr files that should be used when loading a layered resource file on this platform |
public void sendMessage(String[] recipients, String subject, Message msg) | Send an email using the platform mail client. |
public void dial(String phoneNumber) | Opens the device Dialer application with the given phone number |
public boolean isCallDetectionSupported() | Indicates whether this platform can attempt to detect active phone-call interruptions. |
public boolean isInCall() | Best-effort check for whether the platform currently believes an active phone call is interrupting the app. |
public int getSMSSupport() | Indicates the level of SMS support in the platform as one of: #SMS_NOT_SUPPORTED (for desktop, tablet etc.), #SMS_SEAMLESS (no UI interaction), #SMS_INTERACTIVE (with compose UI), #SMS_BOTH. |
public void sendSMS(String phoneNumber, String message)
throws IOException | Sends a SMS message to the given phone number |
public void sendSMS(String phoneNumber, String message, boolean interactive)
throws IOException | Sends a SMS message to the given phone number, the code below demonstrates the logic of detecting platform behavior for sending SMS. |
public void notifyStatusBar(String tickerText, String contentTitle, String contentBody, boolean vibrate, boolean flashLights) | Deprecated Place a notification on the device status bar (if device has this functionality). |
public boolean isNotificationSupported() | Indicates whether the notify status bar method will present a notification to the user |
public Object notifyStatusBar(String tickerText, String contentTitle, String contentBody, boolean vibrate, boolean flashLights, Hashtable args) | Deprecated Place a notification on the device status bar (if device has this functionality). |
public void dismissNotification(Object o) | Removes the notification previously posted with the notify status bar method |
public boolean isBadgingSupported() | Returns true if the underlying OS supports numeric badges on icons. |
public void setBadgeNumber(int number) | Sets the number that appears on the application icon in iOS |
public boolean isOpenNativeNavigationAppSupported() | Returns true if the underlying OS supports opening the native navigation application |
public void openNativeNavigationApp(double latitude, double longitude) | Opens the native navigation app in the given coordinate. |
public void openNativeNavigationApp(String location) | Opens the native navigation app with the given search location |
public String[] getAllContacts(boolean withNumbers) | Gets all contacts from the address book of the device |
public Contact[] getAllContacts(boolean withNumbers, boolean includesFullName, boolean includesPicture, boolean includesNumbers, boolean includesEmail, boolean includeAddress) | Notice: this method might be very slow and should be invoked on a separate thread! It might have platform specific optimizations over getAllContacts followed by looping over individual contacts but that isn’t guaranteed. |
public boolean isGetAllContactsFast() | Indicates if the getAllContacts is platform optimized, notice that the method might still take seconds or more to run so you should still use a separate thread! |
public String[] getLinkedContactIds(Contact c) | Gets IDs of all contacts that are linked to a given contact. |
public Contact getContactById(String id) | Get a Contact according to it’s contact id. |
public Contact getContactById(String id, boolean includesFullName, boolean includesPicture, boolean includesNumbers, boolean includesEmail, boolean includeAddress) | This method returns a Contact by the contact id and fills it’s data according to the given flags. |
public boolean isContactsPermissionGranted() | Some platforms allow the user to block contacts access on a per application basis this method returns true if the user denied permission to access contacts. |
public boolean isContactPickerSupported() | Returns true when the platform has a contact picker, see com.codename1.contacts.ContactPicker. |
public void pickContacts(int requestedFields, boolean multiSelect, int selectionLimit, boolean requireAllRequestedFields, ActionListener<ActionEvent> response) | Shows the platform’s contact picker, see com.codename1.contacts.ContactPicker for the API applications should use and for what the arguments mean. |
public String createContact(String firstName, String familyName, String officePhone, String homePhone, String cellPhone, String email) | Create a contact to the device contacts book |
public boolean deleteContact(String id) | removed a contact from the device contacts book |
public boolean isNativeVideoPlayerControlsIncluded() | Indicates if the native video player includes its own play/pause etc. controls so the movie player component doesn’t need to include them |
public boolean isNativeShareSupported() | Indicates if the underlying platform supports sharing capabilities |
public boolean isNativeInAppReviewSupported() | Indicates whether the platform exposes a native in-app review/rating prompt (the OS-sanctioned “rate this app” sheet). |
public void requestNativeInAppReview(SuccessCallback<Boolean> done) | Requests the native in-app review prompt. |
public void share(String toShare) | Deprecated Share the required information using the platform sharing services. |
public void share(String text, String image, String mimeType) | Share the required information using the platform sharing services. |
public void share(String textOrPath, String image, String mimeType, Rectangle sourceRect) | Share the required information using the platform sharing services. |
public void share(String textOrPath, String image, String mimeType, Rectangle sourceRect, ShareResultListener listener) | Like share(String,String,String,Rectangle) but reports the outcome through listener on the EDT. |
public boolean isPrintingSupported() | Indicates if the underlying platform can print documents through print(String,String,PrintResultListener). |
public void print(String filePath, String mimeType, PrintResultListener listener) | Print a document file through the platform printing system, typically showing the native print dialog where the user picks a printer and options. |
public L10NManager getLocalizationManager() | The localization manager allows adapting values for display in different locales thru parsing and formatting capabilities (similar to JavaSE’s DateFormat/NumberFormat). |
public void registerPush(String id, boolean noFallback) | Deprecated User register to receive push notification |
public void registerPush(Hashtable metaData, boolean noFallback) | Deprecated Register to receive push notification, invoke this method once (ever) to receive push notifications. |
public void registerPush() | Register to receive push notification, invoke this method once (ever) to receive push notifications. |
public void deregisterPush() | Stop receiving push notifications to this client application |
public Media createMediaRecorder(String path)
throws IOException | Creates a Media recorder Object which will record from the device mic to a file in the given path. |
public Media createMediaRecorder(MediaRecorderBuilder builder)
throws IOException | Deprecated |
public Media createMediaRecorder(String path, String mimeType)
throws IOException | Creates a Media recorder Object which will record from the device mic to a file in the given path. |
public boolean isSpeechRecognitionSupported() | Whether SpeechRecognizer is implemented on the current platform. |
public void startSpeechRecognition(RecognitionOptions options, RecognitionCallback callback) | Begins a speech-recognition session. |
public void stopSpeechRecognition() | |
public boolean isTextToSpeechSupported() | Whether TextToSpeech is implemented on the current platform. |
public void textToSpeechSpeak(String text, TtsOptions options) | |
public void textToSpeechStop() | |
public String[] textToSpeechAvailableVoices() | |
public ImageIO getImageIO() | Returns the image IO instance that allows scaling image files. |
public VideoIO getVideoIO() | Returns the video IO instance for video encoding and frame accurate decoding, or null if video IO isn’t supported on the given platform. |
public String getMediaRecorderingMimeType() | Deprecated Gets the recording mime type for the returned Media from the createMediaRecorder method |
public Database openOrCreate(String databaseName)
throws IOException | Opens a database or create one if not exists. |
public Database openOrCreate(String databaseName, DatabaseConfig config)
throws IOException | Opens an encrypted database or creates one if it does not exist. |
public boolean isDatabaseEncryptionSupported() | Indicates whether this platform can open encrypted databases. |
public Database openOrCreateForRekey(String databaseName)
throws IOException | Opens a plaintext database through an engine able to encrypt it in place. |
public boolean isDatabaseManagedKeyHardwareBacked() | Indicates whether managed database keys are held in hardware backed storage here. |
public String databaseManagedKeyIdentity(String databaseName) | Reports whether a database is encrypted, when the platform can tell without reading the file itself. |
public String databaseRegistryIdentity(String databaseName) | See com.codename1.impl.CodenameOneImplementation#databaseRegistryIdentity(String). |
public boolean isRelativeAttachmentNameResolvable() | See com.codename1.impl.CodenameOneImplementation#isRelativeAttachmentNameResolvable(). |
public String databaseIdentityForEngineFile(String engineFile) | See com.codename1.impl.CodenameOneImplementation#databaseIdentityForEngineFile(String). |
public int openDatabaseConnections(String databaseName) | See com.codename1.impl.CodenameOneImplementation#openDatabaseConnections(String). |
public int isDatabaseFileEncrypted(String databaseName) | |
public boolean isBlobQueryParameterSupported() | Indicates whether byte[] values may be used as query parameters. |
public boolean isDatabaseCustomPathSupported() | Indicates whether this platform accepts a file path as a database name. |
public void delete(String databaseName)
throws IOException | Deletes database |
public boolean exists(String databaseName) | Indicates weather a database exists |
public String getDatabasePath(String databaseName) | Returns the file path of the Database if support for database exists on the platform. |
public void setPollingFrequency(int freq) | Deprecated Sets the frequency for polling the server in case of polling based push notification |
public Thread createThread(Runnable r, String name) | Start a Codename One thread that supports crash protection and similar Codename One features. |
public Thread startThread(Runnable r, String name) | Deprecated Start a Codename One thread that supports crash protection and similar Codename One features. |
public boolean isNativeTitle() | Indicates if the title of the Form is native title(in android ICS devices if the command behavior is native the ActionBar is used to display the title and the menu) |
public void refreshNativeTitle() | if the title is native(e.g the android action bar), notify the native title that is needs to be refreshed |
public CrashReport getCrashReporter() | The crash reporter gets invoked when an uncaught exception is intercepted |
public void setCrashReporter(CrashReport crashReporter) | The crash reporter gets invoked when an uncaught exception is intercepted |
public String getUdid() | Returns the UDID for devices that support it |
public String getMsisdn() | Returns the MSISDN for devices that expose it |
public Purchase getInAppPurchase() | Returns the native OS purchase implementation if applicable, if unavailable this method will try to fallback to a custom purchase implementation and failing that will return null |
public Purchase getInAppPurchase(boolean d) | Deprecated |
public CodeScanner getCodeScanner() | Deprecated Returns the native implementation of the code scanner or null |
public String[] getAvailableRecordingMimeTypes() | Gets the available recording MimeTypes |
public boolean isScreenSaverDisableSupported() | Checks if the device supports disabling the screen display from dimming, allowing the developer to keep the screen display on. |
public boolean isScrollWheeling() | Checks is the scroll-wheel mouse is currently scrolling. |
public void setScreenSaverEnabled(boolean e) | If isScreenSaverDisableSupported() returns true calling this method will lock the screen display on |
public boolean hasCamera() | Returns true if the device has camera false otherwise. |
public boolean isNativePickerTypeSupported(int pickerType) | Indicates whether the native picker dialog is supported for the given type which can include one of PICKER_TYPE_DATE_AND_TIME, PICKER_TYPE_TIME, PICKER_TYPE_DATE |
public Object showNativePicker(int type, Component source, Object currentValue, Object data) | Shows a native modal dialog allowing us to perform the picking for the given type which can include one of PICKER_TYPE_DATE_AND_TIME, PICKER_TYPE_TIME, PICKER_TYPE_DATE |
public boolean isMultiKeyMode() | When set to true Codename One allows multiple hardware keys to be pressed at once, this isn’t on by default since it can trigger some complexities with UI navigation to/from native code |
public void setMultiKeyMode(boolean multiKeyMode) | When set to true Codename One allows multiple hardware keys to be pressed at once, this isn’t on by default since it can trigger some complexities with UI navigation to/from native code |
public int getLongPointerPressInterval() | Long pointer press is invoked after the given interval, this allows making long press events shorter/longer |
public void setLongPointerPressInterval(int v) | Long pointer press is invoked after the given interval, this allows making long press events shorter/longer |
public void scheduleLocalNotification(LocalNotification n, long firstTime, int repeat) | Schedules a local notification that will occur after the given time elapsed. |
public void cancelLocalNotification(String notificationId) | Cancels a local notification by ID. |
public void requestNotificationPermission(NotificationPermissionCallback callback) | Requests permission to post notifications using a default request (alert, sound and badge). |
public void requestNotificationPermission(NotificationPermissionRequest request, NotificationPermissionCallback callback) | Requests permission to post notifications with the capabilities described by the given request. |
public void registerNotificationChannel(NotificationChannelBuilder builder) | Registers a notification channel (Android). |
public void deleteNotificationChannel(String channelId) | Deletes a notification channel (Android). |
public void createNotificationChannelGroup(String groupId, String groupName) | Creates a notification channel group (Android). |
public void scheduleBackgroundWork(WorkRequest request) | Schedules constraint-aware background work. |
public void cancelBackgroundWork(String workId) | Cancels scheduled background work by id. |
public boolean isBackgroundWorkSupported() | Returns true if constraint-aware background work is supported. |
public void scheduleBackgroundProcessing(String id, long earliestBeginEpochMs, boolean requiresNetwork, boolean requiresPower, Runnable task) | Schedules a deferrable background processing task. |
public void cancelBackgroundProcessing(String id) | Cancels a scheduled background processing task. |
public boolean isBackgroundProcessingSupported() | Returns true if deferrable background processing is supported. |
public Object startForegroundService(String channelId, String title, String body, String iconName, ForegroundService.Task task, ForegroundService handle) | Starts a foreground service. |
public void updateForegroundServiceNotification(Object nativeHandle, String title, String body) | Updates a foreground service notification. |
public void stopForegroundService(Object nativeHandle) | Stops a foreground service. |
public boolean isForegroundServiceSupported() | Returns true if foreground services are supported. |
public boolean isReceiveSharedContentSupported() | Returns true if the platform can receive shared content from other apps. |
public boolean isWalletExtensionSupported() | Returns true if the platform supports publishing data to a Wallet issuer-provisioning extension. |
public void walletExtensionSetPassEntries(boolean remote, WalletPassEntry[] entries) | Publishes the Wallet extension pass entries, replacing the previous list. |
public void walletExtensionSetRequiresAuthentication(boolean requiresAuthentication) | Sets the Wallet extension requires-authentication flag. |
public void walletExtensionSetAuthToken(String token) | Publishes the Wallet extension auth token. |
public void walletExtensionClear() | Clears all published Wallet extension data. |
public void subscribeToPushTopic(String topic) | Subscribes the device to a push topic. |
public void unsubscribeFromPushTopic(String topic) | Unsubscribes the device from a push topic. |
public void setPreferredBackgroundFetchInterval(int seconds) | Sets the preferred time interval between background fetches. |
public int getPreferredBackgroundFetchInterval(int seconds) | Gets the preferred time (in seconds) between background fetches. |
public boolean isBackgroundFetchSupported() | Checks to see if the current platform supports background fetch. |
public boolean isSimulator() | Allows detecting development mode so debugging code and special cases can be used to simplify flow |
public boolean isDebuggableBuild() | Whether this build is a development build rather than a release build headed for an app store. |
public Media createBackgroundMedia(String uri)
throws IOException | Creates an audio media that can be played in the background. |
public AsyncResource<Media> createBackgroundMediaAsync(String uri) | Creates an audio media that can be played in the background. |
public Image gaussianBlurImage(Image image, float radius) | Create a blur image from the given image. |
public Image createSFSymbolImage(String name, int color, float sizePixels, int weight) | Renders an Apple SF Symbol to an image on iOS (null elsewhere / if the symbol is unavailable). |
public boolean isGaussianBlurSupported() | Returns true if gaussian blur is supported on this platform |
public void refreshContacts() | Refreshes the native list of contacts on devices that require this see com.codename1.contacts.ContactsManager#refresh() |
public boolean isJailbrokenDevice() | Returns true if this device is jailbroken or rooted, false if not or unknown. |
public AsyncResource<String> requestIntegrityToken(String nonce) | Requests a signed device-attestation token (Play Integrity / App Attest) bound to the server nonce. |
public boolean isAttestationSupported() | Returns true if device-attestation (Play Integrity / App Attest) is supported and bundled. |
public boolean isDeviceCompromised() | Non-exiting RASP check, true if the device appears rooted/jailbroken/instrumented/tampered. |
public String[] getCompromiseReasons() | Returns the reason codes behind isDeviceCompromised() (e.g. “root”, “frida”, “emulator”). |
public String[] getEnabledAccessibilityServices() | Returns the component ids of the accessibility services currently enabled on the device. |
public void resetAttestation() | Discards cached platform attestation state, forcing the next attestation to start from a fresh hardware key. |
public void confirmAttestation(String keyId) | Acknowledges that a backend recorded the attested key. |
public String[] getAppSignerDigests() | Returns digests of the certificates the running app is signed with. |
public void setSecureScreen(boolean secure) | Marks the current screen secure (Android FLAG_SECURE), blocking screenshots/recording/scraping. |
public void setTapjackingProtection(TapjackingPolicy policy) | Sets the tapjacking policy. |
public TapjackingPolicy getTapjackingPolicy() | The tapjacking policy currently in force, never null. |
public boolean isScreenObscured() | True when the most recently observed touch arrived over an obscured window. |
public void addTapjackingListener(ActionListener l) | Registers a listener notified when the obscured state changes. |
public void removeTapjackingListener(ActionListener l) | Removes a listener added by addTapjackingListener(). |
public void setHideOverlayWindows(boolean hide) | Asks the OS to hide overlay windows drawn over this app (Android 12+). |
public boolean isHideOverlayWindowsSupported() | True where setHideOverlayWindows() is actually enforced by the platform. |
public Map<String, String> getProjectBuildHints() | Returns the build hints for the simulator, this will only work in the debug environment and it’s designed to allow extensions/API’s to verify user settings/build hints exist |
public void setProjectBuildHint(String key, String value) | Sets a build hint into the settings while overwriting any previous value. |
public boolean canInstallOnHomescreen() | Checks to see if you can prompt the user to install the app on their homescreen. |
public boolean promptInstallOnHomescreen() | Prompts the user to install this app on their homescreen. |
public void onCanInstallOnHomescreen(Runnable r) | A callback fired when you are allowed to prompt the user to install the app on their homescreen. |
public Image captureScreen() | Deprecated Captures a screenshot of the screen. |
public void screenshot(SuccessCallback<Image> callback) | Captures a screenshot in the native layer which should include peer components as well. |
public void notifyPushCompletion() | Notifies the platform that push notification processing is complete. |
public Timer setTimeout(int timeout, Runnable r) | Convenience method to schedule a task to run on the EDT after timeoutms. |
public Timer setInterval(int period, Runnable r) | Convenience method to schedule a task to run on the EDT after periodms repeating every periodms. |
public BrowserComponent getSharedJavascriptContext() | Gets a reference to an application-wide shared Javascript context that can be used for running Javascript commands. |
public void firePinchBeginGesture() | Starts a magnify (pinch) gesture. |
public void firePinchReleaseGesture(int x, int y) | Ends the magnify (pinch) gesture in progress, notifying whichever component consumed it. |
Inherited fields
From CN1Constants
DENSITY_VERY_LOW, DENSITY_LOW, DENSITY_MEDIUM, DENSITY_HIGH, DENSITY_VERY_HIGH, DENSITY_HD, DENSITY_560, DENSITY_2HD, DENSITY_4K, PICKER_TYPE_DATE, PICKER_TYPE_TIME, PICKER_TYPE_DATE_AND_TIME, PICKER_TYPE_STRINGS, PICKER_TYPE_DURATION, PICKER_TYPE_DURATION_HOURS, PICKER_TYPE_DURATION_MINUTES, PICKER_TYPE_CALENDAR, SMS_NOT_SUPPORTED, SMS_SEAMLESS, SMS_INTERACTIVE, SMS_BOTH, GALLERY_IMAGE, GALLERY_VIDEO, GALLERY_ALL, GALLERY_IMAGE_MULTI, GALLERY_VIDEO_MULTI, GALLERY_ALL_MULTI
Inherited methods
Field details
SOUND_TYPE_ALARM
public static final String SOUND_TYPE_ALARM = "alarm"SOUND_TYPE_CONFIRMATION
public static final String SOUND_TYPE_CONFIRMATION = "confirmation"SOUND_TYPE_ERROR
public static final String SOUND_TYPE_ERROR = "error"SOUND_TYPE_INFO
public static final String SOUND_TYPE_INFO = "info"SOUND_TYPE_WARNING
public static final String SOUND_TYPE_WARNING = "warning"SOUND_TYPE_BUTTON_PRESS
public static final String SOUND_TYPE_BUTTON_PRESS = "press"KEYBOARD_TYPE_UNKNOWN
public static final int KEYBOARD_TYPE_UNKNOWN = 0KEYBOARD_TYPE_NUMERIC
public static final int KEYBOARD_TYPE_NUMERIC = 1KEYBOARD_TYPE_QWERTY
public static final int KEYBOARD_TYPE_QWERTY = 2KEYBOARD_TYPE_VIRTUAL
public static final int KEYBOARD_TYPE_VIRTUAL = 3KEYBOARD_TYPE_HALF_QWERTY
public static final int KEYBOARD_TYPE_HALF_QWERTY = 4GAME_FIRE
public static final int GAME_FIRE = 8GAME_LEFT
public static final int GAME_LEFT = 2GAME_RIGHT
public static final int GAME_RIGHT = 5GAME_UP
public static final int GAME_UP = 1GAME_DOWN
public static final int GAME_DOWN = 6MEDIA_KEY_SKIP_FORWARD
public static final int MEDIA_KEY_SKIP_FORWARD = 20MEDIA_KEY_SKIP_BACK
public static final int MEDIA_KEY_SKIP_BACK = 21MEDIA_KEY_PLAY
public static final int MEDIA_KEY_PLAY = 22MEDIA_KEY_STOP
public static final int MEDIA_KEY_STOP = 23MEDIA_KEY_PLAY_STOP
public static final int MEDIA_KEY_PLAY_STOP = 24MEDIA_KEY_PLAY_PAUSE
public static final int MEDIA_KEY_PLAY_PAUSE = 25MEDIA_KEY_FAST_FORWARD
public static final int MEDIA_KEY_FAST_FORWARD = 26MEDIA_KEY_FAST_BACKWARD
public static final int MEDIA_KEY_FAST_BACKWARD = 27KEY_POUND
public static final int KEY_POUND = 35SHOW_DURING_EDIT_IGNORE
public static final int SHOW_DURING_EDIT_IGNORE = 1SHOW_DURING_EDIT_EXCEPTION
public static final int SHOW_DURING_EDIT_EXCEPTION = 2SHOW_DURING_EDIT_ALLOW_DISCARD
public static final int SHOW_DURING_EDIT_ALLOW_DISCARD = 3SHOW_DURING_EDIT_ALLOW_SAVE
public static final int SHOW_DURING_EDIT_ALLOW_SAVE = 4SHOW_DURING_EDIT_SET_AS_NEXT
public static final int SHOW_DURING_EDIT_SET_AS_NEXT = 5COMMAND_BEHAVIOR_DEFAULT
public static final int COMMAND_BEHAVIOR_DEFAULT = 1COMMAND_BEHAVIOR_SOFTKEY
public static final int COMMAND_BEHAVIOR_SOFTKEY = 2COMMAND_BEHAVIOR_TOUCH_MENU
public static final int COMMAND_BEHAVIOR_TOUCH_MENU = 3COMMAND_BEHAVIOR_BUTTON_BAR
public static final int COMMAND_BEHAVIOR_BUTTON_BAR = 4COMMAND_BEHAVIOR_BUTTON_BAR_TITLE_BACK
public static final int COMMAND_BEHAVIOR_BUTTON_BAR_TITLE_BACK = 5COMMAND_BEHAVIOR_BUTTON_BAR_TITLE_RIGHT
public static final int COMMAND_BEHAVIOR_BUTTON_BAR_TITLE_RIGHT = 6COMMAND_BEHAVIOR_ICS
public static final int COMMAND_BEHAVIOR_ICS = 7COMMAND_BEHAVIOR_SIDE_NAVIGATION
public static final int COMMAND_BEHAVIOR_SIDE_NAVIGATION = 8COMMAND_BEHAVIOR_NATIVE
public static final int COMMAND_BEHAVIOR_NATIVE = 10WINDOW_SIZE_HINT_PERCENT
public static final String WINDOW_SIZE_HINT_PERCENT = "cn1.windowSizePercent"Form to indicate the desired initial
window size as a percentage of the available desktop. The value should be a com.codename1.ui.geom.Dimension
whose width and height represent percentages.Method details
init
public static void init(Object m)deinitialize
public static void deinitialize()isInitialized
public static boolean isInitialized()Returns
getInstance
public static Display getInstance()Returns
setBookmark
public void setBookmark(Runnable bookmark)Sets a bookmark that can restore the app to a particular state. This takes a
Runnable that will be run when #restoreToBookmark() () } is called.
The primary purpose of this feature is live code refresh.
Parameters
bookmarkRunnable- A
Runnablethat can be run to restore the app to a particular point.
restoreToBookmark
public void restoreToBookmark()#setBookmark(java.lang.Runnable)getPluginSupport
public PluginSupport getPluginSupport()Returns
getDragStartPercentage
public int getDragStartPercentage()Returns
setDragStartPercentage
public void setDragStartPercentage(int dragStartPercentage)Parameters
dragStartPercentageint- percentage of the screen required to initiate drag
getWifiPlatform
public WifiPlatform getWifiPlatform()com.codename1.io.wifi.WiFi; applications normally talk to that
static facade rather than calling this directly.getWifiDirectPlatform
public WifiDirectPlatform getWifiDirectPlatform()getBonjourPlatform
public BonjourPlatform getBonjourPlatform()getUsbPlatform
public UsbPlatform getUsbPlatform()getNetworkTypePlatform
public NetworkTypePlatform getNetworkTypePlatform()NetworkManager.addNetworkTypeListener(...).getSimd
public Simd getSimd()isGpuSupported
public boolean isGpuSupported()com.codename1.gpu.RenderView.createGpuPeer
public PeerComponent createGpuPeer(RenderView view)RenderView. Intended for use by
RenderView; returns null on platforms without a 3D backend.gpuSetContinuous
public void gpuSetContinuous(PeerComponent peer, boolean continuous)RenderView.gpuRequestRender
public void gpuRequestRender(PeerComponent peer)RenderView.setFramerate
public void setFramerate(int rate)Parameters
rateint- the frame rate
vibrate
public void vibrate(int duration)Parameters
durationint- length of time to vibrate (might be ignored)
flashBacklight
public void flashBacklight(int duration)Parameters
durationint- length of time to flash the backlight
announceForAccessibility
public void announceForAccessibility(Component cmp, String text)Parameters
cmpComponent- the component related to this announcement or
nullfor the root view textString- the message to announce
announceForAccessibility
public void announceForAccessibility(String text)Parameters
textString- the message to announce
accessibilityTreeChanged
public void accessibilityTreeChanged(int changeType)Parameters
changeTypeint- bit mask of
AccessibilityManager.CHANGE_*constants
accessibilityTreeChanged
public void accessibilityTreeChanged(int changeType, int windowId)Parameters
changeTypeint- bit mask of
AccessibilityManager.CHANGE_*constants windowIdint- the surface that changed, zero for the application’s main one
isAccessibilityTreeSupported
public boolean isAccessibilityTreeSupported()isAccessibilityTreeUpdateRequired
public boolean isAccessibilityTreeUpdateRequired()getShowDuringEditBehavior
public int getShowDuringEditBehavior()Returns
setShowDuringEditBehavior
public void setShowDuringEditBehavior(int showDuringEdit)Parameters
showDuringEditint- one of the following: SHOW_DURING_EDIT_IGNORE, SHOW_DURING_EDIT_EXCEPTION, SHOW_DURING_EDIT_ALLOW_DISCARD, SHOW_DURING_EDIT_ALLOW_SAVE, SHOW_DURING_EDIT_SET_AS_NEXT
getFrameRate
public int getFrameRate()Returns
isEdt
public boolean isEdt()Returns
stopRemoteControl
public void stopRemoteControl()Stops the remote control service. This should be implemented in the platform
to handle unbinding the com.codename1.media.RemoteControlListener with the platform’s remote control.
This is executed when a new listener is registered using com.codename1.media.MediaManager#setRemoteControlListener(com.codename1.media.RemoteControlListener)
startRemoteControl
public void startRemoteControl()Starts the remote control service. This should be implemented
in the platform to handle binding the RemoteControlListener with
the platform’s remote control.
This is executed when the user registers a new listener using MediaManager#setRemoteControlListener(com.codename1.media.RemoteControlListener)
isDarkMode
public Boolean isDarkMode()Returns
setDarkMode
public void setDarkMode(Boolean darkMode)Parameters
darkModeBoolean- can be set to null to reset to platform default
isLargerTextEnabled
public boolean isLargerTextEnabled()Returns
getLargerTextScale
public float getLargerTextScale()1.0 indicates the default system font size.Returns
isHighContrastEnabled
public boolean isHighContrastEnabled()isDifferentiateWithoutColorEnabled
public boolean isDifferentiateWithoutColorEnabled()getColorVisionDeficiency
public AccessibilityColorVisionDeficiency getColorVisionDeficiency()AccessibilityColorVisionDeficiency.UNKNOWN
when the platform doesn’t expose it.isReduceMotionEnabled
public boolean isReduceMotionEnabled()isReduceTransparencyEnabled
public boolean isReduceTransparencyEnabled()isBoldTextEnabled
public boolean isBoldTextEnabled()isInvertColorsEnabled
public boolean isInvertColorsEnabled()isGrayscaleEnabled
public boolean isGrayscaleEnabled()isOnOffSwitchLabelsEnabled
public boolean isOnOffSwitchLabelsEnabled()isScreenReaderEnabled
public boolean isScreenReaderEnabled()isEnableAsyncStackTraces
public boolean isEnableAsyncStackTraces()Checks if async stack traces are enabled. If enabled, the stack trace
at the point of #callSerially(java.lang.Runnable) calls will
be recorded, and logged in the case that there is an uncaught exception.
Currently this is only supported in the JavaSE/Simulator port.
Returns
setEnableAsyncStackTraces
public void setEnableAsyncStackTraces(boolean enableAsyncStackTraces)Enables or disables async stack traces. If enabled, the stack trace
at the point of #callSerially(java.lang.Runnable) calls will
be recorded, and logged in the case that there is an uncaught exception.
Currently this is only supported in the JavaSE/Simulator port.
Parameters
enableAsyncStackTracesboolean- True to enable async stack traces.
See also
callSerially
public void callSerially(Runnable r)Parameters
rRunnable- runnable (NOT A THREAD!) that will be invoked on the EDT serial to the paint and key handling events
callSeriallyOnIdle
public void callSeriallyOnIdle(Runnable r)Parameters
rRunnable- runnable (NOT A THREAD!) that will be invoked on the EDT serial to the paint and key handling events
getLineSeparator
public String getLineSeparator()scheduleBackgroundTask
public void scheduleBackgroundTask(Runnable r)Parameters
rRunnable- the task to perform in the background
callSeriallyAndWait
public void callSeriallyAndWait(Runnable r)Parameters
rRunnable- runnable (NOT A THREAD!) that will be invoked on the EDT serial to the paint and key handling events
Throws
IllegalStateException- if this method is invoked on the event dispatch thread (e.g. during paint or event handling).
platformUsesInputMode
public boolean platformUsesInputMode()Returns
callSeriallyAndWait
public void callSeriallyAndWait(Runnable r, int timeout)Parameters
rRunnable- runnable (NOT A THREAD!) that will be invoked on the EDT serial to the paint and key handling events
timeoutint- timeout duration, on timeout the method just returns
Throws
IllegalStateException- if this method is invoked on the event dispatch thread (e.g. during paint or event handling).
isInTransition
public boolean isInTransition()Returns
getStackTrace
public String getStackTrace(Thread parentThread, Throwable t)Parameters
parentThreadThread- the thread in which the exception was thrown
tThrowable- the exception
Returns
onEditingComplete
public void onEditingComplete(Component c, String text)Parameters
cComponent- edited component
textString- new text for the component
invokeWithoutBlocking
public void invokeWithoutBlocking(Runnable r)#invokeAndBlock(java.lang.Runnable) from inside this Runnable,
it will result in a BlockingDisallowedException being thrown.Parameters
rRunnable- Runnable to be run immediately.
Throws
BlockingDisallowedException- If
#invokeAndBlock(java.lang.Runnable)is attempted anywhere in the Runnable.
invokeWithoutBlockingWithResultSync
public <T> T invokeWithoutBlockingWithResultSync(RunnableWithResultSync<T> r)#invokeAndBlock(java.lang.Runnable) from inside this Runnable,
it will result in a BlockingDisallowedException being thrown.Parameters
rRunnableWithResultSync<T>- RunnableWithResultSync to be run immediately.
Throws
BlockingDisallowedException- If
#invokeAndBlock(java.lang.Runnable)is attempted anywhere in the Runnable.
invokeAndBlock
public void invokeAndBlock(Runnable r, boolean dropEvents)Invokes runnable and blocks the current thread, if the current thread is the EDT it will still be blocked in a way that doesn’t break event dispatch . Important: calling this method spawns a new thread that shouldn’t access the UI!
See this section in the developer guide for further information.
Parameters
rRunnable- runnable (NOT A THREAD!) that will be invoked synchronously by this method
dropEventsboolean- indicates if the display should drop all events while this runnable is running
Throws
BlockingDisallowedException- if this method is called while blocking is disabled (i.e. we are running
inside a call to
#invokeWithoutBlocking(java.lang.Runnable)on the EDT).
invokeAndBlock
public void invokeAndBlock(Runnable r)Invokes runnable and blocks the current thread, if the current thread is the EDT it will still be blocked in a way that doesn’t break event dispatch . Important: calling this method spawns a new thread that shouldn’t access the UI!
See this section in the developer guide for further information.
Parameters
rRunnable- runnable (NOT A THREAD!) that will be invoked synchroniously by this method
isTouchScreenDevice
public boolean isTouchScreenDevice()Returns
setTouchScreenDevice
public void setTouchScreenDevice(boolean touchScreen)Parameters
touchScreenboolean- false if this is not a touch screen device
setNoSleep
public void setNoSleep(boolean noSleep)Parameters
noSleepboolean- causes the edt to stop the sleeping periods between 2 cycles
setTransitionYield
public void setTransitionYield(int transitionD)Parameters
transitionDint- -1 for no delay otherwise delay in milliseconds
editString
public void editString(Component cmp, int maxSize, int constraint, String text)com.codename1.ui.TextArea#startEditingAsync(), com.codename1.ui.TextArea#startEditing()
or com.codename1.ui.Form#setEditOnShow(com.codename1.ui.TextArea).Parameters
cmpComponent- the
TextAreacomponent maxSizeint- the maximum size from the text area
constraintint- the constraints of the text area
textString- the string to edit
editString
public void editString(Component cmp, int maxSize, int constraint, String text, int initiatingKeycode)com.codename1.ui.TextArea#startEditingAsync(), com.codename1.ui.TextArea#startEditing()
or com.codename1.ui.Form#setEditOnShow(com.codename1.ui.TextArea).Parameters
cmpComponent- the
TextAreacomponent maxSizeint- the maximum size from the text area
constraintint- the constraints of the text area
textString- the string to edit
initiatingKeycodeint- the keycode used to initiate the edit.
stopEditing
public void stopEditing(Component cmp)Parameters
cmpComponent- the text field/text area component
stopEditing
public void stopEditing(Component cmp, Runnable onFinish)Form, it will stop editing in any active
component on the form, and close the keyboard if it is opened.Parameters
cmpComponent- the text field/text area component
onFinishRunnable- invoked when editing stopped
minimizeApplication
public boolean minimizeApplication()Returns
isMinimized
public boolean isMinimized()Returns
restoreMinimizedApplication
public void restoreMinimizedApplication()isControlKeyDown
public boolean isControlKeyDown()isMetaKeyDown
public boolean isMetaKeyDown()isAltKeyDown
public boolean isAltKeyDown()isAltGraphKeyDown
public boolean isAltGraphKeyDown()isRightMouseButtonDown
public boolean isRightMouseButtonDown()Returns
isShiftKeyDown
public boolean isShiftKeyDown()getCurrentPointerEvent
public PointerEvent getCurrentPointerEvent()Returns a snapshot of the rich detail for the pointer event currently being dispatched such as the mouse button, pointer type (finger/mouse/stylus), pressure and stylus tilt.
This is most useful when called from within a pointer listener. When no pointer event has been dispatched yet a default snapshot at the last known pointer location is returned.
Returns
PointerEvent, never nullgetPointerButton
public int getPointerButton()PointerEvent BUTTON_* constants.getPressedButtonMask
public int getPressedButtonMask()PointerEvent MASK_* constants.getPointerType
public int getPointerType()PointerEvent TYPE_*
constants (finger, mouse, stylus or eraser).getPointerPressure
public float getPointerPressure()0.0 and 1.0. Devices and
ports that do not report pressure return 1.0.getPointerTiltX
public float getPointerTiltX()0 when not reported.getPointerTiltY
public float getPointerTiltY()0 when not reported.getPointerContactSize
public float getPointerContactSize()0.0 and 1.0, or 0 when not reported.isStylusPointer
public boolean isStylusPointer()fireMouseWheelEvent
public boolean fireMouseWheelEvent(int x, int y, int scrollX, int scrollY, boolean precise, int modifiers)Dispatches a mouse wheel event to the component under the given coordinates, and scrolls it. Invoked by the implementation on the EDT.
This is where a wheel ends: listeners on the component and its ancestors see it first and
may consume it, then Component#mouseWheel(com.codename1.ui.events.WheelEvent) may take
it, and what neither claimed scrolls the nearest ancestor that can move in that direction.
A port calls this and does nothing else.
It used to dispatch to listeners only, as a preflight before the port synthesized a press, a few drags and a release to do the scrolling. Those synthetic events are gone – they pressed whatever sat under the cursor, so a trackpad nudge over a button activated it – and the scrolling they existed for happens here instead. The method is deliberately the single terminal entry point rather than one of a pair: a port that called the wrong half of a split API would either scroll nothing or go back to faking pointer events, which is the bug this replaced.
Parameters
xint- the pointer x position in display pixels
yint- the pointer y position in display pixels
scrollXint- the horizontal scroll amount in display pixels
scrollYint- the vertical scroll amount in display pixels
preciseboolean- true if the deltas come from a high resolution device such as a trackpad
modifiersint- bitmask of the held keyboard modifiers
Returns
fireMagnifyGesture
public void fireMagnifyGesture(int x, int y, float scale)com.codename1.ui.Component#pinch(float).Parameters
xint- the gesture x position in display pixels
yint- the gesture y position in display pixels
scalefloat- the magnification scale, larger than 1 zooms in and smaller than 1 zooms out
fireRotationGesture
public void fireRotationGesture(int x, int y, float radians)com.codename1.ui.Component#rotation(float).Parameters
xint- the gesture x position in display pixels
yint- the gesture y position in display pixels
radiansfloat- the incremental rotation in radians, positive is clockwise
keyPressed
public void keyPressed(int keyCode)Parameters
keyCodeint- keycode of the key event
keyReleased
public void keyReleased(int keyCode)Parameters
keyCodeint- keycode of the key event
pointerDragged
public void pointerDragged(int[] x, int[] y)Parameters
xint[]- the x position of the pointer
yint[]- the y position of the pointer
pointerHover
public void pointerHover(int[] x, int[] y)Parameters
xint[]- the x position of the pointer
yint[]- the y position of the pointer
pointerHoverPressed
public void pointerHoverPressed(int[] x, int[] y)Parameters
xint[]- the x position of the pointer
yint[]- the y position of the pointer
pointerHoverReleased
public void pointerHoverReleased(int[] x, int[] y)Parameters
xint[]- the x position of the pointer
yint[]- the y position of the pointer
pointerPressed
public void pointerPressed(int[] x, int[] y)Parameters
xint[]- the x position of the pointer
yint[]- the y position of the pointer
pointerReleased
public void pointerReleased(int[] x, int[] y)Parameters
xint[]- the x position of the pointer
yint[]- the y position of the pointer
sizeChanged
public void sizeChanged(int w, int h)Parameters
wint- the width of the drawing surface
hint- the height of the drawing surface
hideNotify
public void hideNotify()showNotify
public void showNotify()hasDragOccured
public boolean hasDragOccured()Returns
getCurrentTopLevel
public TopLevelContainer getCurrentTopLevel()Returns
getCurrent
public Form getCurrent()#getCurrentTopLevel()
for the answer that can also name a Window.numAlphaLevels
public int numAlphaLevels()Returns
numColors
public int numColors()Returns
getDisplayWidth
public int getDisplayWidth()Returns
getDisplayHeight
public int getDisplayHeight()Returns
getDesktopSize
public Dimension getDesktopSize()Returns
getWindowBounds
public Rectangle getWindowBounds()Returns
setWindowSize
public void setWindowSize(int width, int height)Parameters
widthint- the desired window width
heightint- the desired window height
getInitialWindowSizeHintPercent
public Dimension getInitialWindowSizeHintPercent()Returns
nullsetInitialWindowSizeHintPercent
public void setInitialWindowSizeHintPercent(Dimension hint)Parameters
hintDimension- a
Dimensionwhose width/height represent percentages of the desktop to use for the initial window size, ornullto clear a previously stored hint
convertToPixels
public int convertToPixels(int dipCount, boolean horizontal)Parameters
dipCountint- the dips that we will convert to pixels
horizontalboolean- indicates pixels in the horizontal plane
Returns
convertToPixels
public int convertToPixels(float value, byte unitType)Parameters
valuefloat- The value to convert, expressed in unitType.
unitTypebyte- The unit type. One of
Style#UNIT_TYPE_DIPS,Style#UNIT_TYPE_PIXELS,Style#UNIT_TYPE_REM,Style#UNIT_TYPE_SCREEN_PERCENTAGE,Style#UNIT_TYPE_VH,Style#UNIT_TYPE_VW,Style#UNIT_TYPE_VMIN,Style#UNIT_TYPE_VMAX
Returns
convertToPixels
public int convertToPixels(float value, byte unitType, boolean horizontal)Parameters
valuefloat- The value to convert, expressed in unitType.
unitTypebyte- The unit type. One of
Style#UNIT_TYPE_DIPS,Style#UNIT_TYPE_PIXELS,Style#UNIT_TYPE_REM,Style#UNIT_TYPE_SCREEN_PERCENTAGE,Style#UNIT_TYPE_VH,Style#UNIT_TYPE_VW,Style#UNIT_TYPE_VMIN,Style#UNIT_TYPE_VMAX horizontalboolean- Whether screen percentage units should be based on horitonzal or vertical percentage.
Returns
convertToPixels
public int convertToPixels(float dipCount)Parameters
dipCountfloat- the dips that we will convert to pixels
Returns
getGameAction
public int getGameAction(int keyCode)Parameters
keyCodeint- key code received from the event
Returns
getKeyCode
public int getKeyCode(int gameAction)Parameters
gameActionint- game action constant from this class
Returns
isThirdSoftButton
public boolean isThirdSoftButton()Returns
setThirdSoftButton
public void setThirdSoftButton(boolean thirdSoftButton)Parameters
thirdSoftButtonboolean- true if a third softbutton should be used
setShowVirtualKeyboard
public void setShowVirtualKeyboard(boolean show)com.codename1.ui.TextArea#startEditingAsync() or com.codename1.ui.TextArea#stopEditing()
to control text field editing/VKB visibilityParameters
showboolean- toggles the virtual keyboards visibility
isVirtualKeyboardShowing
public boolean isVirtualKeyboardShowing()com.codename1.ui.TextArea#isEditing() instead.Returns
getSupportedVirtualKeyboard
public String[] getSupportedVirtualKeyboard()Returns
registerVirtualKeyboard
public void registerVirtualKeyboard(VirtualKeyboardInterface vkb)getDefaultVirtualKeyboard
public VirtualKeyboardInterface getDefaultVirtualKeyboard()Returns
setDefaultVirtualKeyboard
public void setDefaultVirtualKeyboard(VirtualKeyboardInterface vkb)Parameters
vkbVirtualKeyboardInterface- a VirtualKeyboard to be used or null to disable the VirtualKeyboard
getVirtualKeyboardListener
public ActionListener getVirtualKeyboardListener()#removeVirtualKeyboardListener(com.codename1.ui.events.ActionListener)Returns
setVirtualKeyboardListener
public void setVirtualKeyboardListener(ActionListener l)#addVirtualKeyboardListener(com.codename1.ui.events.ActionListener)Parameters
lActionListener- the listener
addVirtualKeyboardListener
public void addVirtualKeyboardListener(ActionListener l)Adds a listener for VirtualKeyboard hide/show events. ActionEvents will return a Boolean
value for ActionEvent#getSource(), with Boolean.TRUE on show, and Boolean.FALSE
on hide.
Note: Keyboard events may not be 100% reliable as they use heuristics on most platforms to guess when the keyboard is shown or hidden.
Parameters
lActionListener- The listener.
removeVirtualKeyboardListener
public void removeVirtualKeyboardListener(ActionListener l)Removes a listener for VirtualKeyboard hide/show events. ActionEvents will return a Boolean
value for ActionEvent#getSource(), with Boolean.TRUE on show, and Boolean.FALSE
on hide.
Note: Keyboard events may not be 100% reliable as they use heuristics on most platforms to guess when the keyboard is shown or hidden.
Parameters
lActionListener- The listener.
fireVirtualKeyboardEvent
public void fireVirtualKeyboardEvent(boolean show)getInvisibleAreaUnderVKB
public int getInvisibleAreaUnderVKB()Returns
getKeyboardType
public int getKeyboardType()Returns
isNativeInputSupported
public boolean isNativeInputSupported()Returns
isMultiTouch
public boolean isMultiTouch()Returns
isClickTouchScreen
public boolean isClickTouchScreen()Indicates whether the device has a double layer screen thus allowing two stages to touch events: click and hover. This is true for devices such as the storm but can also be true for a PC with a mouse pointer floating on top.
A click touch screen will also send pointer hover events to the underlying software and will only send the standard pointer events on click.
Returns
getDragSpeed
public float getDragSpeed(boolean yAxis)Parameters
yAxisboolean- indicates what axis speed is required
Returns
isBidiAlgorithm
public boolean isBidiAlgorithm()Returns
setBidiAlgorithm
public void setBidiAlgorithm(boolean activate)Parameters
activateboolean- set to true to activate the bidi algorithm, false to disable it
convertBidiLogicalToVisual
public String convertBidiLogicalToVisual(String s)Parameters
sString- a “logical” string with RTL characters
Returns
getCharLocation
public int getCharLocation(String source, int index)Parameters
sourceString- the string in which we are looking for the position
indexint- the “logical” location of the cursor
Returns
isRTL
public boolean isRTL(char c)Parameters
cchar- character to test
Returns
getResourceAsStream
public InputStream getResourceAsStream(Class cls, String resource)Parameters
clsClass- class to load the resource from
resourceString- relative/absolute URL based on the Java convention
Returns
addEdtErrorHandler
public void addEdtErrorHandler(ActionListener e)Parameters
eActionListener- listener receiving the errors
getNativeLogSnapshot
public String getNativeLogSnapshot()installNativeCrashHandler
public void installNativeCrashHandler()consumePendingNativeCrash().
Idempotent.consumePendingNativeCrash
public String consumePendingNativeCrash()installNativeCrashHandler(),
or null if none. The implementation deletes the underlying
record before returning so the same crash isn’t replayed on
subsequent launches. Crash protection wraps the returned blob
in a synthetic report payload.removeEdtErrorHandler
public void removeEdtErrorHandler(ActionListener e)isAllowMinimizing
public boolean isAllowMinimizing()Returns
setAllowMinimizing
public void setAllowMinimizing(boolean allowMinimizing)Parameters
allowMinimizingboolean- value
shouldRenderSelection
public boolean shouldRenderSelection()Returns
shouldRenderSelection
public boolean shouldRenderSelection(Component c)isPureTouch
public boolean isPureTouch()Returns
setPureTouch
public void setPureTouch(boolean pureTouch)Parameters
pureTouchboolean- the value for pureTouch
isNativeCommands
public boolean isNativeCommands()Returns
setNativeCommands
public void setNativeCommands(boolean nativeCommands)Parameters
nativeCommandsboolean- the flag to set
exitApplication
public void exitApplication()exitAndClearTask
public void exitAndClearTask()Activity.finishAndRemoveTask(); platforms that expose no equivalent (iOS, the desktop
ports and the simulator among them) fall back to #exitApplication(), which is why the
call is always safe to make. Use #isExitAndClearTaskSupported() when the behavior
matters enough to branch on.isExitAndClearTaskSupported
public boolean isExitAndClearTaskSupported()#exitAndClearTask() is still legal, it just behaves
exactly like #exitApplication().Returns
See also
isFullScreenSupported
public boolean isFullScreenSupported()Checks if this platform supports full-screen mode. If full-screen mode is supported, you can use
the #requestFullScreen(), #exitFullScreen(), and #isInFullScreenMode() methods
to enter and exit full-screen - and query the current state.
Currently only desktop and Javascript builds support full-screen mode; And Javascript only supports this on certain browsers. See the MDN Fullscreen API docs for a list of browsers that support full-screen.
When running in the simulator, full-screen is only supported for the desktop skin.
Returns
requestFullScreen
public boolean requestFullScreen()Try to enter full-screen mode if the platform supports it.
Currently only desktop and Javascript builds support full-screen mode; And Javascript only supports this on certain browsers. See the MDN Fullscreen API docs for a list of browsers that support full-screen.
When running in the simulator, full-screen is only supported for the desktop skin.
Returns
exitFullScreen
public boolean exitFullScreen()Try to exit full-screen mode if the platform supports it.
Currently only desktop and Javascript builds support full-screen mode; And Javascript only supports this on certain browsers. See the MDN Fullscreen API docs for a list of browsers that support full-screen.
When running in the simulator, full-screen is only supported for the desktop skin.
Returns
isInFullScreenMode
public boolean isInFullScreenMode()Returns
showNativeScreen
public void showNativeScreen(Object nativeFullScreenPeer)Parameters
nativeFullScreenPeerObject- the native screen peer
isAutoFoldVKBOnFormSwitch
public boolean isAutoFoldVKBOnFormSwitch()Returns
setAutoFoldVKBOnFormSwitch
public void setAutoFoldVKBOnFormSwitch(boolean autoFoldVKBOnFormSwitch)Parameters
autoFoldVKBOnFormSwitchboolean- the autoFoldVKBOnFormSwitch to set
getCommandBehavior
public int getCommandBehavior()Toolbar API. When using the toolbar the command
behavior can’t be manipulatedReturns
setCommandBehavior
public void setCommandBehavior(int commandBehavior)Toolbar API. When using the toolbar the command
behavior can’t be manipulatedParameters
commandBehaviorint- the commandBehavior to set
postMessage
public void postMessage(MessageEvent message)Posts a message to the native platform. Different platforms may handle messages posted this way differently.
The Javascript port will dispatch the message on the window object as a custom DOM event named ‘cn1outbox’, with the event data containing a ‘detail’ key with the message, and a ‘code’ key with the code.
Parameters
messageMessageEvent- The message.
addMessageListener
public void addMessageListener(ActionListener<MessageEvent> l)Adds a listener to receive messages from the native platform. This is one mechanism for the native platform to communicate with the Codename one app.
In the JavaScript port, listeners will be notified when DOM events named ‘cn1inbox’ are received on the window object. The event data ‘detail’ key will be the source of the message, and the ‘code’ key will be the source of the code.
Parameters
lActionListener<MessageEvent>- The listener.
removeMessageListener
public void removeMessageListener(ActionListener<MessageEvent> l)Parameters
lActionListener<MessageEvent>- The listener.
dispatchMessage
public void dispatchMessage(MessageEvent evt)addWindowListener
public void addWindowListener(ActionListener<WindowEvent> l)Parameters
lActionListener<WindowEvent>- the listener to add
removeWindowListener
public void removeWindowListener(ActionListener<WindowEvent> l)Parameters
lActionListener<WindowEvent>- the listener to remove
fireWindowEvent
public void fireWindowEvent(WindowEvent evt)Parameters
evtWindowEvent- the window event to dispatch
getProperty
public String getProperty(String key, String defaultValue)Returns the property from the underlying platform deployment or the default value if no deployment values are supported. This is equivalent to the getAppProperty from the jad file.
The implementation should be responsible for the following keys to return reasonable valid values for the application:
AppName
User-Agent
AppVersion
Platform - Similar to microedition.platform
OS - returns what is the underlying platform e.g. - iOS, Android, RIM, SE…
OSVer - OS version when available as a user readable string (not necessarily a number e.g: 3.2.1).
Parameters
keyString- the key of the property
defaultValueString- a default return value
Returns
isApnsPushDevice
public boolean isApnsPushDevice()Whether this port’s device subscribes to push through APNs.
A capability, so it is answered by the port and not by
#getProperty(String, String): cn1_push_prefix is a key an
application may legitimately set – Push.getPushKey() reads exactly
that override – and letting the override answer here sent provider
“native” for a device that registers with APNs, so no deliverable
subscription was ever created.
Narrow on purpose. The generic port-property accessor behind it stays package private: an application has no business reading arbitrary implementation properties, and every widening of that surface is permanent.
Returns
isNativeRedirects
public boolean isNativeRedirects()Whether this port follows HTTP redirects below the portable network layer, so the framework cannot see where a download actually came from.
A capability for the same reason as #isApnsPushDevice(): it decides
whether a model download must be digest pinned, and reading it through
#getProperty(String, String) would let application or library code
switch that verification off.
Returns
setProperty
public void setProperty(String key, String value)Parameters
keyString- key the key of the property
valueString- the value of the property
canExecute
public Boolean canExecute(String url)Returns true if executing this URL should work, returns false if it will not and null if this is unknown.
Boolean can = Display.getInstance().canExecute("imdb:///find?q=godfather");
if(can != null && can) {
Display.getInstance().execute("imdb:///find?q=godfather");
} else {
Display.getInstance().execute("http://www.imdb.com");
}
Parameters
urlString- the url that would be executed
Returns
execute
public void execute(String url)Executes the given URL on the native platform.
Boolean can = Display.getInstance().canExecute("imdb:///find?q=godfather");
if(can != null && can) {
Display.getInstance().execute("imdb:///find?q=godfather");
} else {
Display.getInstance().execute("http://www.imdb.com");
}
On the JavaSE simulator this method also serves as the cross-platform
entry point for the simulator hook system. The simulator scans cn1libs
(and the running app) for META-INF/codenameone/simulator-hooks.properties
files, and a URL of the form namespace:itemN that matches a registered
hook is intercepted and dispatched on the CN1 EDT instead of being
handed to the native URL opener. On Android, iOS, JavaScript and other
production targets no hooks are ever registered, so a hook-style URL
falls through to the normal native execute and (almost always) becomes
a no-op. CN1 UnitTests running cross-platform should guard with
canExecute(String) before invoking a hook URL:
if (Boolean.TRUE.equals(Display.getInstance().canExecute("bluetooth:item1"))) {
Display.getInstance().execute("bluetooth:item1"); // toggle the simulated adapter
}
See the developer guide’s “Creating CN1Libs” chapter for the
simulator-hooks.properties format and the positional itemN / labelN
conventions.
JavaScript port
Browsers only let a page open a new window/tab from inside a live user
gesture, and Codename One dispatches events on its own EDT so by the time
your listener calls this method the browser no longer considers a gesture
to be in progress. The JavaScript port therefore resolves the
javascript.execute.target property to decide what to do:
auto(the default) opens a new tab when the page still has user activation and otherwise navigates the page the app is running in. No confirmation prompt is ever shown, but note that navigating the current page unloads the app._blankonly ever opens a new tab. When the browser would block it the port shows a confirmationSheetwhose OK button supplies the missing gesture. This was the behavior before the property existed._selfalways navigates the page the app is running in.
Set it before the call, for example in your init method:
Display.getInstance().setProperty("javascript.execute.target", "_self");
The property applies to any URL carrying a URI scheme the browser can
hand off, custom deep links like the imdb:///find example above
included. It is ignored on every other platform, and on all targets a
javascript: URL, a data: URL, a file: URL or a path into local
storage keeps its existing meaning.
Parameters
urlString- the url to execute
execute
public void execute(String url, ActionListener response)Parameters
urlString- the url to execute
responseActionListener- a callback from the platform when this execution returned to the application
downloadBytesAsFile
public boolean downloadBytesAsFile(String fileName, byte[] bytes)execute(String)
download path is unavailable. Returns true if the platform
handled the download, false if unsupported (callers should then
fall back to writing the file and calling execute(String)).Parameters
fileNameString- the suggested file name for the download
bytesbyte[]- the file contents
getDeviceDensity
public int getDeviceDensity()Returns
getDevicePixelRatio
public float getDevicePixelRatio()The platform’s logical-pixel scale factor – device pixels per logical pixel, what
iOS calls UIScreen.scale and Android calls density.
Distinct from getDeviceDensity, which is a coarse DPI bucket for choosing
artwork and physical sizing. Code that lays out in the platform’s own logical units
needs this number: on iOS the scale is 1, 2 or 3, while the density bucket of a
modern iPhone implies 3.5.
Returns
isRoundedImageSupported
public boolean isRoundedImageSupported()Whether this platform can round a picture’s corners as it draws it, rather than the caller having to build a rounded copy of the bitmap.
The platform answering yes does not mean every picture can be rounded –
procedural images and rotated ones cannot. Ask
Graphics.isRoundedImageSupported(Image) about the specific picture
before skipping a rounded-copy fallback.
Returns
Graphics.drawImageRounded(Image, int, int, int, int, float) roundsgetDensityStr
public String getDensityStr()Returns the device density as a string.
DENSITY_VERY_LOW : “very-low”
DENSITY_LOW : “low”
DENSITY_MEDIUM : “medium”
DENSITY_HIGH : “high”
DENSITY_VERY_HIGH : “very-high”
DENSITY_HD : “hd”
DENSITY_560 : “560”
DENSITY_2HD : “2hd”
DENSITY_4K : “4k”;
Returns
See also
playBuiltinSound
public void playBuiltinSound(String soundIdentifier)Parameters
soundIdentifierString- the sound identifier which can match one of the common constants in this class or be a user/implementation defined sound
getDisplaySafeArea
public Rectangle getDisplaySafeArea(Rectangle rect)Parameters
rectRectangle- Out parameter that will store the display safe area.
Returns
See also
installBuiltinSound
public void installBuiltinSound(String soundIdentifier, InputStream data)
throws IOExceptionParameters
soundIdentifierString- the sound string passed to playBuiltinSound
dataInputStream- an input stream containing platform specific audio file, its usually safe to assume that wav/mp3 would be supported.
Throws
IOException- if the stream throws an exception
isBuiltinSoundAvailable
public boolean isBuiltinSoundAvailable(String soundIdentifier)Parameters
soundIdentifierString- the sound string passed to playBuiltinSound
Returns
isBuiltinSoundsEnabled
public boolean isBuiltinSoundsEnabled()Returns
setBuiltinSoundsEnabled
public void setBuiltinSoundsEnabled(boolean enabled)Parameters
enabledboolean- indicates whether the sound is muted
createMedia
public Media createMedia(String uri, boolean isVideo, Runnable onCompletion)
throws IOExceptionParameters
uriString- the platform specific location for the sound
isVideoboolean- Not documented.
onCompletionRunnable- invoked when the audio file finishes playing, may be null
Returns
Throws
java.io.IOException- if the URI access fails
createMediaAsync
public AsyncResource<Media> createMediaAsync(String uri, boolean video, Runnable onCompletion)Parameters
uriString- the platform specific location for the sound
videoboolean- Not documented.
onCompletionRunnable- invoked when the audio file finishes playing, may be null
Returns
addCompletionHandler
public void addCompletionHandler(Media media, Runnable onCompletion)Parameters
mediaMedia- The media to add the callback to.
onCompletionRunnable- The callback that will run on the EDT when the playback completes.
removeCompletionHandler
public void removeCompletionHandler(Media media, Runnable onCompletion)Parameters
mediaMedia- The media element.
onCompletionRunnable- The callback.
createMedia
public Media createMedia(InputStream stream, String mimeType, Runnable onCompletion)
throws IOExceptionParameters
streamInputStream- the stream containing the media data
mimeTypeString- the type of the data in the stream
onCompletionRunnable- invoked when the audio file finishes playing, may be null
Returns
Throws
java.io.IOException- if the URI access fails
createMediaAsync
public AsyncResource<Media> createMediaAsync(InputStream stream, String mimeType, Runnable onCompletion)isSoundPoolSupported
public boolean isSoundPoolSupported()com.codename1.gaming.SoundPool. When false the gaming layer uses a
com.codename1.media.MediaManager based fallback.createSoundPool
public SoundPoolPeer createSoundPool(int maxStreams)com.codename1.gaming.SoundPool,
or returns null when this platform has no native backend.Parameters
maxStreamsint- the maximum number of simultaneously playing voices
createSoftWeakRef
public Object createSoftWeakRef(Object o)Parameters
oObject- object to cache
Returns
extractHardRef
public Object extractHardRef(Object o)Parameters
oObject- the reference returned by createSoftWeakRef
Returns
hasNativeTheme
public boolean hasNativeTheme()Returns
installNativeTheme
public void installNativeTheme()copyToClipboard
public void copyToClipboard(Object obj)Parameters
objObject- object to copy, while this can be any arbitrary object it is recommended that only Strings or Codename One image objects be used to copy
copyToClipboard
public void copyToClipboard(ClipboardContent content)text/plain; richer consumers can negotiate HTML, RTF, Markdown, AsciiDoc, or custom MIME data.getPasteDataFromClipboard
public Object getPasteDataFromClipboard()Returns
getClipboardContent
public ClipboardContent getClipboardContent()isPortrait
public boolean isPortrait()Returns
isLockOrientation
public boolean isLockOrientation()Returns
canForceOrientation
public boolean canForceOrientation()Returns true if the device allows forcing the orientation via code, feature phones do not allow this although some include a jad property allowing for this feature
Since version 6.0, orientation lock is supported in Javascript builds in some browsers. For a full list of browsers the support locking orientation, see the MDN Lock Orientation docs.
NOTE: In Javascript builds, orientation lock is only supported if the app is running in full-screen mode. If the app is not
currently in full-screen mode, then #canForceOrientation() will return false and #lockOrientation(boolean) will do nothing.
Returns
lockOrientation
public void lockOrientation(boolean portrait)On devices that return true for canForceOrientation() this method can lock the device orientation either to portrait or landscape mode
Since version 6.0, orientation lock is supported in Javascript builds in some browsers. For a full list of browsers the support locking orientation, see the MDN Lock Orientation docs.
NOTE: In Javascript builds, orientation lock is only supported if the app is running in full-screen mode. If the app is not
currently in full-screen mode, then #canForceOrientation() will return false and #lockOrientation(boolean) will do nothing.
Parameters
portraitboolean- true to lock to portrait mode, false to lock to landscape mode
unlockOrientation
public void unlockOrientation()This is the reverse method for lock orientation allowing orientation lock to be disabled
Since version 6.0, orientation lock is supported in Javascript builds in some browsers. For a full list of browsers the support locking orientation, see the MDN Lock Orientation docs.
NOTE: In Javascript builds, orientation lock is only supported if the app is running in full-screen mode. If the app is not
currently in full-screen mode, then #canForceOrientation() will return false and #lockOrientation(boolean) will do nothing.
isTablet
public boolean isTablet()Returns
isDesktop
public boolean isDesktop()Returns
isWatch
public boolean isWatch()Returns
isTV
public boolean isTV()Returns
isCarConnected
public boolean isCarConnected()com.codename1.car experience. See com.codename1.car.Car#isCarConnected().Returns
isFoldable
public boolean isFoldable()Returns
getDevicePosture
public DevicePosture getDevicePosture()com.codename1.ui.DevicePosture for details.Returns
addPostureListener
public void addPostureListener(ActionListener l)com.codename1.ui.events.ActionEvent has the type PostureChange; query the new
posture from com.codename1.ui.DevicePosture#getInstance().Parameters
lActionListener- the listener to add
removePostureListener
public void removePostureListener(ActionListener l)Parameters
lActionListener- the listener to remove
postureChanged
public void postureChanged()isDesktopMode
public boolean isDesktopMode()#isDesktop() which
reports a genuine desktop platform (Windows, macOS or Linux).Returns
getDisplayCount
public int getDisplayCount()Returns
isExternalDisplayConnected
public boolean isExternalDisplayConnected()Returns
getCarBridge
public CarBridge getCarBridge()com.codename1.car API to render in-car templates, or
null when in-car projection is unsupported on this port. Internal – application code uses the
com.codename1.car API rather than this bridge directly.Returns
getWearableBridge
public WearableBridge getWearableBridge()com.codename1.wearable API to talk to the
counterpart watch or phone app, or null when this device has no wearable counterpart.
Internal – application code uses the com.codename1.wearable API rather than this bridge
directly.Returns
getHomeBridge
public HomeBridge getHomeBridge()com.codename1.home API to reach HomeKit, the
Google Home APIs or a local simulated home, or null when this port has no smart-home
support. Internal – application code uses com.codename1.home.SmartHome rather than this
bridge directly.Returns
getNearbyBridge
public NearbyBridge getNearbyBridge()com.codename1.nearby API to reach precision
ranging, companion-device association and the nearby transport, or null when this port
implements none of them. Internal – application code uses the com.codename1.nearby
packages rather than this bridge directly.Returns
getCallBridge
public CallBridge getCallBridge()com.codename1.call API to reach the system call
stack – CallKit and PushKit on iOS, ConnectionService and TelecomManager on Android –
or null when unsupported on this port. Internal – application code uses the
com.codename1.call packages rather than this bridge directly.Returns
getVpnBridge
public VpnBridge getVpnBridge()com.codename1.vpn API to manage VPN
configurations, or null when unsupported on this port. Internal – application code uses
the com.codename1.vpn packages rather than this bridge directly.Returns
getSurfaceBridge
public SurfaceBridge getSurfaceBridge()com.codename1.surfaces API to render external
surfaces (home-screen widgets and live activities), or null when unsupported on this port.
Internal – application code uses the com.codename1.surfaces API rather than this bridge
directly.Returns
getDocumentProviderBridge
public DocumentProviderBridge getDocumentProviderBridge()com.codename1.documents API to expose the
application’s documents to the system file browser, or null when unsupported on this port.
Internal – application code uses the com.codename1.documents API rather than this bridge
directly.Returns
getContinuityBridge
public ContinuityBridge getContinuityBridge()com.codename1.continuity API to advertise the
user’s current activity to their other devices and to reach the platform’s synced key/value
store, or null when unsupported on this port. Internal – application code uses the
com.codename1.continuity API rather than this bridge directly.Returns
getIntentBridge
public IntentBridge getIntentBridge()com.codename1.intents API to expose the
application’s capabilities to the system, or null when unsupported on this port. Internal –
application code uses the com.codename1.intents API rather than this bridge directly.Returns
canDial
public boolean canDial()Returns
areMutableImagesFast
public boolean areMutableImagesFast()Returns
getLocationManager
public LocationManager getLocationManager()This method returns the platform Location Manager used for geofencing. This allows tracking the user location in the background. Usage:
// File: BGLocationTest.java
public void showForm() {
Form hi = new Form("Hi World");
hi.addComponent(new Label("Hi World"));
Location loc = new Location();
loc.setLatitude(51.5033630);
loc.setLongitude(-0.1276250);
Geofence gf = new Geofence("test", loc, 100, 100000);
LocationManager.getLocationManager().addGeoFencing(GeofenceListenerImpl.class, gf);
hi.show();
}
// File: GeofenceListenerImpl.java
public class GeofenceListenerImpl implements GeofenceListener {
public void onExit(String id) {
System.out.println("Exited "+id);
}
public void onEntered(String id) {
System.out.println("Entered "+id);
}
}
`public class GeofenceListenerImpl implements GeofenceListener {
public void onExit(String id) {
System.out.println("Exited "+id);`
public void onEntered(String id) {
System.out.println("Entered "+id);
}
}
Form hi = new Form("Hi World");
hi.addComponent(new Label("Hi World"));
Location loc = new Location();
loc.setLatitude(51.5033630);
loc.setLongitude(-0.1276250);
Geofence gf = new Geofence("test", loc, 100, 100000);
LocationManager.getLocationManager().addGeoFencing(GeofenceListenerImpl.class, gf);
hi.show();}
Returns
isLocationButtonSupported
public boolean isLocationButtonSupported()Whether this platform draws a location button of its own.
From Android 17 Google Play requires transactional precise-location use
to go through a button the system draws, because a tap on such a button
is what earns a session-scoped grant. Where there is no such control this
returns false and LocationButton falls back to
an ordinary Codename One button that asks for the location permission.
This is the question to ask BEFORE building anything – what the
platform can do. What a particular button ended up showing is
com.codename1.location.LocationButton#isSystemRendered(), which also
answers false when the platform has the control but its session
failed.
Returns
createLocationButton can produce a controlcreateLocationButton
public PeerComponent createLocationButton(int textType, int backgroundColor, int textColor, SuccessCallback<Boolean> onPermissionResult)Builds the platform’s own location button.
This is the platform half of LocationButton,
which is what application code uses; it is public for the same reason
createGpuPeer is, so a port and the component can meet.
Parameters
textTypeint- one of the
TEXT_constants onLocationButton backgroundColorint- an RRGGBB colour for the control, or -1 to let the platform choose
textColorint- an RRGGBB colour for its label, or -1 to let the platform choose
onPermissionResultSuccessCallback<Boolean>- invoked with TRUE when the user shared their location, FALSE when they declined, and null when the platform’s own session failed
Returns
isLocationButtonReady
public boolean isLocationButtonReady(PeerComponent button)Whether a control from createLocationButton is actually live.
The platform half of
com.codename1.location.LocationButton#isSystemRendered(). A control
the system renders in another process exists before it is drawn into,
and a session that never opens leaves it existing and blank.
Parameters
buttonPeerComponent- a control this platform returned
Returns
getMotionSensorManager
public MotionSensorManager getMotionSensorManager()null when the
current port does not provide motion sensors. Prefer
MotionSensorManager.getInstance() in
application code — it handles the fallback to a no-op manager when the
current port returns null.getBiometrics
public Biometrics getBiometrics()Biometrics.getInstance() in application
code — it handles the fallback to a no-op stub when the current port
does not implement biometrics.getSecureStorage
public SecureStorage getSecureStorage()SecureStorage.getInstance() in
application code.getNfc
public Nfc getNfc()Nfc.getInstance() in application code —
it handles the fallback to a no-op stub when the current port does
not implement NFC.getLocalCalendarSource
public LocalCalendarSource getLocalCalendarSource()LocalCalendarSource.getInstance().getBluetooth
public Bluetooth getBluetooth()Bluetooth.getInstance() in
application code — it handles the fallback to a no-op stub when
the current port does not implement Bluetooth.getHealth
public Health getHealth()Health.getInstance() in application
code — it handles the fallback to a no-op stub when the current
port does not implement health data.capturePhoto
public void capturePhoto(ActionListener response)This method tries to invoke the device native camera to capture images. The method returns immediately and the response will be sent asynchronously to the given ActionListener Object The image is saved as a jpeg to a file on the device.
use this in the actionPerformed to retrieve the file path String path = (String) evt.getSource();
if evt returns null the image capture was cancelled by the user.
Parameters
responseActionListener- a callback Object to retrieve the file path
Throws
RuntimeException- if this feature failed or unsupported on the platform
captureAudio
public void captureAudio(ActionListener<ActionEvent> response)This method tries to invoke the device native hardware to capture audio. The method returns immediately and the response will be sent asynchronously to the given ActionListener Object The audio is saved to a file on the device.
use this in the actionPerformed to retrieve the file path String path = (String) evt.getSource();
Parameters
responseActionListener<ActionEvent>- a callback Object to retrieve the file path
Throws
RuntimeException- if this feature failed or unsupported on the platform
captureAudio
public void captureAudio(MediaRecorderBuilder recordingOptions, ActionListener response)This method tries to invoke the device native hardware to capture audio. The method returns immediately and the response will be sent asynchronously to the given ActionListener Object The audio is saved to a file on the device.
use this in the actionPerformed to retrieve the file path String path = (String) evt.getSource();
Parameters
recordingOptionsMediaRecorderBuilder- Audio recording options.
responseActionListener- a callback Object to retrieve the file path
Throws
RuntimeException- if this feature failed or unsupported on the platform
captureVideo
public void captureVideo(ActionListener response)This method tries to invoke the device native camera to capture video. The method returns immediately and the response will be sent asynchronously to the given ActionListener Object The video is saved to a file on the device.
use this in the actionPerformed to retrieve the file path String path = (String) evt.getSource();
Parameters
responseActionListener- a callback Object to retrieve the file path
Throws
RuntimeException- if this feature failed or unsupported on the platform
captureVideo
public void captureVideo(VideoCaptureConstraints constraints, ActionListener response)#captureVideo(com.codename1.ui.events.ActionListener), except that it
attempts to impose constraints on the capture. Constraints include width, height,
and max length. Not all platforms support capture constraints. Use the VideoCaptureConstraints#isSupported()
to see if a constraint is supported. If constraints are not supported at all, then this method
will fall back to calling #captureVideo(com.codename1.ui.events.ActionListener).Parameters
constraintsVideoCaptureConstraints- Capture constraints to use.
responseActionListener- a callback Object to retrieve the file path
openImageGallery
public void openImageGallery(ActionListener response)Opens the device image gallery The method returns immediately and the response will be sent asynchronously to the given ActionListener Object
use this in the actionPerformed to retrieve the file path String path = (String) evt.getSource();
Parameters
responseActionListener- a callback Object to retrieve the file path
Throws
RuntimeException- if this feature failed or unsupported on the platform
openGallery
public void openGallery(ActionListener response, int type)Opens the device gallery to pick an image or a video.
The method returns immediately and the response is sent asynchronously to the given ActionListener Object as the source value of the event (as a String)
E.g. within the callback action performed call you can use this code: String path = (String) evt.getSource();.
A more detailed sample of picking a video file can be seen here:
final Form hi = new Form("MediaPlayer", new BorderLayout());
hi.setToolbar(new Toolbar());
Style s = UIManager.getInstance().getComponentStyle("Title");
FontImage icon = FontImage.createMaterial(FontImage.MATERIAL_VIDEO_LIBRARY, s);
hi.getToolbar().addCommandToRightBar(new Command("", icon) {
@Override
public void actionPerformed(ActionEvent evt) {
Display.getInstance().openGallery((e) -> {
if(e != null && e.getSource() != null) {
String file = (String)e.getSource();
try {
Media video = MediaManager.createMedia(file, true);
hi.removeAll();
hi.add(BorderLayout.CENTER, new MediaPlayer(video));
hi.revalidate();
} catch(IOException err) {
Log.e(err);
}
}
}, Display.GALLERY_VIDEO);
}
});
hi.show();
Version 5.0 and higher support multi-selection (i.e. the types #GALLERY_IMAGE_MULTI, #GALLERY_VIDEO_MULTI, and #GALLERY_ALL_MULTI). When using one of the multiselection
types, the source of the ActionEvent will be a String[], containing the paths of the selected elements, or null if the user cancelled the dialog.
Platform support
Currently (version 5.0 and higher), all platforms support the types #GALLERY_IMAGE, #GALLERY_VIDEO, #GALLERY_ALL, #GALLERY_IMAGE_MULTI, #GALLERY_VIDEO_MULTI, #GALLERY_ALL_MULTI. On iOS,
multi-selection requires a deployment target of iOS 8.0 or higher, so it is disabled by default. You can enable multi-selection on iOS, by adding the ios.enableGalleryMultiselect=true build hint. This
build hint will be added automatically for you if you run your app in the simulator, and it calls openGallery() with one of the multiselect gallery types.
Parameters
responseActionListener- a callback Object to retrieve the file path For multiselection types (
#GALLERY_IMAGE_MULTI,#GALLERY_VIDEO_MULTI, and#GALLERY_ALL_MULTI), the source of the ActionEvent sent this callback will be a String[]. For other types, it will be a String. If the dialog was cancelled, it will be null. typeint- one of the following
#GALLERY_IMAGE,#GALLERY_VIDEO,#GALLERY_ALL,#GALLERY_IMAGE_MULTI,#GALLERY_VIDEO_MULTI,#GALLERY_ALL_MULTI.
Throws
RuntimeException- if this feature failed or unsupported on the platform. Use
#isGalleryTypeSupported(int)to check if the type is supported before calling this method.
See also
#isGalleryTypeSupported(int)To see if a type is supported on the current platform.
openFileChooser
public void openFileChooser(ActionListener response, String accept)Opens a file chooser for arbitrary user-selected files.
The callback source is a String path that can be read with
FileSystemStorage.openInputStream(), or null if the user cancelled.
The accept argument is a comma-separated list of file extensions
("pdf,txt", "p8") or MIME types ("application/pdf"). Platforms with
native document pickers use them; other ports fall back to a Codename One
file tree.
Unlike openGallery(), this API is not for media-library access and does
not add photo/music build hints.
Parameters
responseActionListener- callback receiving the selected file path
acceptString- comma-separated extensions or MIME types, or
nullfor all files
isGalleryTypeSupported
public boolean isGalleryTypeSupported(int type)Parameters
typeint- one of the following
#GALLERY_IMAGE,#GALLERY_VIDEO,#GALLERY_ALL,#GALLERY_IMAGE_MULTI,#GALLERY_VIDEO_MULTI,#GALLERY_ALL_MULTI.
Returns
getPlatformName
public String getPlatformName()Returns
getPlatformOverrides
public String[] getPlatformOverrides()Returns
sendMessage
public void sendMessage(String[] recipients, String subject, Message msg)Send an email using the platform mail client.
The code below demonstrates sending a simple message with attachments using the devices native email client:
Message m = new Message("Body of message");
m.getAttachments().put(textAttachmentUri, "text/plain");
m.getAttachments().put(imageAttachmentUri, "image/png");
Display.getInstance().sendMessage(new String[] {"someone@gmail.com"}, "Subject of message", m);
Parameters
recipientsString[]- array of e-mail addresses
subjectString- e-mail subject
msgMessage- the Message to send
dial
public void dial(String phoneNumber)isCallDetectionSupported
public boolean isCallDetectionSupported()Indicates whether this platform can attempt to detect active phone-call interruptions.
A true result means the platform provides a best-effort heuristic only.
It does not guarantee exact telephony state.
Returns
true if call detection is implemented on this platform.isInCall
public boolean isInCall()Best-effort check for whether the platform currently believes an active phone call is interrupting the app.
This API is intentionally heuristic. It can produce false positives (e.g. non-call interruptions like Control Center or app-switching) and false negatives. Use it for UX hints and telemetry, not as a security or business-critical gate.
Returns
true if the platform currently believes a call interruption is active.getSMSSupport
public int getSMSSupport()Indicates the level of SMS support in the platform as one of:
#SMS_NOT_SUPPORTED (for desktop, tablet etc.),
#SMS_SEAMLESS (no UI interaction), #SMS_INTERACTIVE (with compose UI),
#SMS_BOTH.
The sample below demonstrates the use case for this property:
void sendMessage(String phone, String data) {
switch(Display.getInstance().getSMSSupport()) {
case Display.SMS_NOT_SUPPORTED:
return;
case Display.SMS_SEAMLESS:
showUIDialogToEditMessageData();
Display.getInstance().sendSMS(phone, data);
return;
default:
Display.getInstance().sendSMS(phone, data);
return;
}
}
Returns
sendSMS
public void sendSMS(String phoneNumber, String message)
throws IOExceptionParameters
phoneNumberString- to send the sms
messageString- the content of the sms
Throws
sendSMS
public void sendSMS(String phoneNumber, String message, boolean interactive)
throws IOExceptionSends a SMS message to the given phone number, the code below demonstrates the logic of detecting platform behavior for sending SMS.
void sendMessage(String phone, String data) {
switch(Display.getInstance().getSMSSupport()) {
case Display.SMS_NOT_SUPPORTED:
return;
case Display.SMS_SEAMLESS:
showUIDialogToEditMessageData();
Display.getInstance().sendSMS(phone, data);
return;
default:
Display.getInstance().sendSMS(phone, data);
return;
}
}
Parameters
phoneNumberString- to send the sms
messageString- the content of the sms
interactiveboolean- indicates the SMS should show a UI or should not show a UI if applicable see getSMSSupport
Throws
See also
notifyStatusBar
public void notifyStatusBar(String tickerText, String contentTitle, String contentBody, boolean vibrate, boolean flashLights)Parameters
tickerTextString- the ticker text of the Notification
contentTitleString- the title of the Notification
contentBodyString- the content of the Notification
vibrateboolean- enable/disable notification alert
flashLightsboolean- enable/disable notification flashing
isNotificationSupported
public boolean isNotificationSupported()Returns
notifyStatusBar
public Object notifyStatusBar(String tickerText, String contentTitle, String contentBody, boolean vibrate, boolean flashLights, Hashtable args)Parameters
tickerTextString- the ticker text of the Notification
contentTitleString- the title of the Notification
contentBodyString- the content of the Notification
vibrateboolean- enable/disable notification alert
flashLightsboolean- enable/disable notification flashing
argsHashtable- additional arguments to the notification
Returns
dismissNotification
public void dismissNotification(Object o)Parameters
oObject- the object returned from the notifyStatusBar method
isBadgingSupported
public boolean isBadgingSupported()Returns
setBadgeNumber
public void setBadgeNumber(int number)Parameters
numberint- number to show on the icon
getAllContacts
public String[] getAllContacts(boolean withNumbers)Parameters
withNumbersboolean- if true returns only contacts that has a number
Returns
getAllContacts
public Contact[] getAllContacts(boolean withNumbers, boolean includesFullName, boolean includesPicture, boolean includesNumbers, boolean includesEmail, boolean includeAddress)Notice: this method might be very slow and should be invoked on a separate thread! It might have platform specific optimizations over getAllContacts followed by looping over individual contacts but that isn’t guaranteed. See isGetAllContactsFast for information.
The sample below demonstrates listing all the contacts within the device with their photos
Form hi = new Form("Contacts", new BoxLayout(BoxLayout.Y_AXIS));
hi.add(new InfiniteProgress());
int size = Display.getInstance().convertToPixels(5, true);
FontImage fi = FontImage.createFixed("" + FontImage.MATERIAL_PERSON, FontImage.getMaterialDesignFont(), 0xff, size, size);
Display.getInstance().scheduleBackgroundTask(() -> {
Contact[] contacts = Display.getInstance().getAllContacts(true, true, false, true, false, false);
Display.getInstance().callSerially(() -> {
hi.removeAll();
for(Contact c : contacts) {
MultiButton mb = new MultiButton(c.getDisplayName());
mb.setIcon(fi);
mb.setTextLine2(c.getPrimaryPhoneNumber());
hi.add(mb);
mb.putClientProperty("id", c.getId());
Display.getInstance().scheduleBackgroundTask(() -> {
Contact cc = ContactsManager.getContactById(c.getId(), false, true, false, false, false);
Display.getInstance().callSerially(() -> {
Image photo = cc.getPhoto();
if(photo != null) {
mb.setIcon(photo.fill(size, size));
mb.revalidate();
}
});
});
}
hi.getContentPane().animateLayout(150);
});
});
Parameters
withNumbersboolean- if true returns only contacts that has a number
includesFullNameboolean- if true try to fetch the full name of the Contact(not just display name)
includesPictureboolean- if true try to fetch the Contact Picture if exists
includesNumbersboolean- if true try to fetch all Contact numbers
includesEmailboolean- if true try to fetch all Contact Emails
includeAddressboolean- if true try to fetch all Contact Addresses
Returns
isGetAllContactsFast
public boolean isGetAllContactsFast()Returns
getLinkedContactIds
public String[] getLinkedContactIds(Contact c)Parameters
cContact- The contact whose “linked” contacts are to be retrieved.
Returns
getContactById
public Contact getContactById(String id)Parameters
idString- unique id of the Contact
Returns
getContactById
public Contact getContactById(String id, boolean includesFullName, boolean includesPicture, boolean includesNumbers, boolean includesEmail, boolean includeAddress)This method returns a Contact by the contact id and fills it’s data according to the given flags.
The sample below demonstrates listing all the contacts within the device with their photos
Form hi = new Form("Contacts", new BoxLayout(BoxLayout.Y_AXIS));
hi.add(new InfiniteProgress());
int size = Display.getInstance().convertToPixels(5, true);
FontImage fi = FontImage.createFixed("" + FontImage.MATERIAL_PERSON, FontImage.getMaterialDesignFont(), 0xff, size, size);
Display.getInstance().scheduleBackgroundTask(() -> {
Contact[] contacts = Display.getInstance().getAllContacts(true, true, false, true, false, false);
Display.getInstance().callSerially(() -> {
hi.removeAll();
for(Contact c : contacts) {
MultiButton mb = new MultiButton(c.getDisplayName());
mb.setIcon(fi);
mb.setTextLine2(c.getPrimaryPhoneNumber());
hi.add(mb);
mb.putClientProperty("id", c.getId());
Display.getInstance().scheduleBackgroundTask(() -> {
Contact cc = ContactsManager.getContactById(c.getId(), false, true, false, false, false);
Display.getInstance().callSerially(() -> {
Image photo = cc.getPhoto();
if(photo != null) {
mb.setIcon(photo.fill(size, size));
mb.revalidate();
}
});
});
}
hi.getContentPane().animateLayout(150);
});
});
Parameters
idString- of the Contact
includesFullNameboolean- if true try to fetch the full name of the Contact(not just display name)
includesPictureboolean- if true try to fetch the Contact Picture if exists
includesNumbersboolean- if true try to fetch all Contact numbers
includesEmailboolean- if true try to fetch all Contact Emails
includeAddressboolean- if true try to fetch all Contact Addresses
Returns
isContactsPermissionGranted
public boolean isContactsPermissionGranted()Returns
isContactPickerSupported
public boolean isContactPickerSupported()com.codename1.contacts.ContactPicker.Returns
#pickContacts(int, boolean, int, boolean, com.codename1.ui.events.ActionListener)
will show a pickerpickContacts
public void pickContacts(int requestedFields, boolean multiSelect, int selectionLimit, boolean requireAllRequestedFields, ActionListener<ActionEvent> response)com.codename1.contacts.ContactPicker for the API applications should
use and for what the arguments mean.Parameters
requestedFieldsint- bit set of the field constants on
com.codename1.contacts.ContactPicker multiSelectboolean- true to let the user pick more than one contact
selectionLimitint- the largest number of contacts the user may pick
requireAllRequestedFieldsboolean- true to offer only contacts holding every requested field
responseActionListener<ActionEvent>- invoked with a
com.codename1.contacts.Contactarray source once the user is done
createContact
public String createContact(String firstName, String familyName, String officePhone, String homePhone, String cellPhone, String email)Parameters
firstNameString- the Contact firstName
familyNameString- the Contact familyName
officePhoneString- the Contact work phone or null
homePhoneString- the Contact home phone or null
cellPhoneString- the Contact mobile phone or null
emailString- the Contact email or null
Returns
deleteContact
public boolean deleteContact(String id)Parameters
idString- the contact id to remove
Returns
isNativeVideoPlayerControlsIncluded
public boolean isNativeVideoPlayerControlsIncluded()Returns
isNativeInAppReviewSupported
public boolean isNativeInAppReviewSupported()AppReview API falls back to a Codename One
drawn rating widget.Returns
requestNativeInAppReview
public void requestNativeInAppReview(SuccessCallback<Boolean> done)isNativeInAppReviewSupported returns true. The platforms hide whether
the user actually rated and may throttle the prompt; done reports
whether the request reached the native review controller.Parameters
doneSuccessCallback<Boolean>- invoked with
trueonce the native prompt was requested orfalsewhen the platform did not handle it. May be null.
isPrintingSupported
public boolean isPrintingSupported()print(String,String,PrintResultListener).Returns
public void print(String filePath, String mimeType, PrintResultListener listener)Print a document file through the platform printing system,
typically showing the native print dialog where the user picks a
printer and options. The outcome is reported through listener on
the EDT.
All printing platforms accept PDF (application/pdf) and common
image types (image/png, image/jpeg); other mime types fail with
PrintResult.STATUS_FAILED on platforms that can’t render them.
See Printer for a friendlier facade.
Parameters
filePathString- path of the document in
FileSystemStorage mimeTypeString- the document type, e.g.
application/pdf,image/png listenerPrintResultListener- callback for the print outcome. May be null.
getLocalizationManager
public L10NManager getLocalizationManager()The localization manager allows adapting values for display in different locales thru parsing and formatting capabilities (similar to JavaSE’s DateFormat/NumberFormat). It also includes language/locale/currency related API’s similar to Locale/currency API’s from JavaSE.
The sample code below just lists the various capabilities of the API:
Form hi = new Form("L10N", new TableLayout(16, 2));
L10NManager l10n = L10NManager.getInstance();
hi.add("format(double)").add(l10n.format(11.11)).
add("format(int)").add(l10n.format(33)).
add("formatCurrency").add(l10n.formatCurrency(53.267)).
add("formatDateLongStyle").add(l10n.formatDateLongStyle(new Date())).
add("formatDateShortStyle").add(l10n.formatDateShortStyle(new Date())).
add("formatDateTime").add(l10n.formatDateTime(new Date())).
add("formatDateTimeMedium").add(l10n.formatDateTimeMedium(new Date())).
add("formatDateTimeShort").add(l10n.formatDateTimeShort(new Date())).
add("getCurrencySymbol").add(l10n.getCurrencySymbol()).
add("getLanguage").add(l10n.getLanguage()).
add("getLocale").add(l10n.getLocale()).
add("isRTLLocale").add("" + l10n.isRTLLocale()).
add("parseCurrency").add(l10n.formatCurrency(l10n.parseCurrency("33.77$"))).
add("parseDouble").add(l10n.format(l10n.parseDouble("34.35"))).
add("parseInt").add(l10n.format(l10n.parseInt("56"))).
add("parseLong").add("" + l10n.parseLong("4444444"));
hi.show();
Returns
registerPush
public void registerPush(String id, boolean noFallback)#registerPush() the Android push id should be set with the build hint gcm.sender_id which will work for Chrome JavaScript builds tooParameters
idString- the id for the user
noFallbackboolean- some devices don’t support an efficient push API and will resort to polling to provide push like functionality. If this flag is set to true no polling will occur and the error PushCallback.REGISTRATION_ERROR_SERVICE_NOT_AVAILABLE will be sent to the push interface.
registerPush
public void registerPush(Hashtable metaData, boolean noFallback)#registerPush() the Android push id should be set with the build hint gcm.sender_id which will work for Chrome JavaScript builds tooParameters
metaDataHashtable- meta data for push, this is relevant on some platforms such as google where a push id is necessary,
noFallbackboolean- some devices don’t support an efficient push API and will resort to polling to provide push like functionality. If this flag is set to true no polling will occur and the error PushCallback.REGISTRATION_ERROR_SERVICE_NOT_AVAILABLE will be sent to the push interface.
registerPush
public void registerPush()deregisterPush
public void deregisterPush()createMediaRecorder
public Media createMediaRecorder(String path)
throws IOExceptionParameters
pathString- a file path to where to store the recording, if the file does not exists it will be created.
Throws
createMediaRecorder
public Media createMediaRecorder(MediaRecorderBuilder builder)
throws IOExceptionParameters
builderMediaRecorderBuilder- A MediaRecorderBuilder
Returns
Throws
See also
createMediaRecorder
public Media createMediaRecorder(String path, String mimeType)
throws IOExceptionParameters
pathString- a file path to where to store the recording, if the file does not exists it will be created.
mimeTypeString- the output mime type that is supported see getAvailableRecordingMimeTypes()
Throws
isSpeechRecognitionSupported
public boolean isSpeechRecognitionSupported()SpeechRecognizer is implemented
on the current platform. The user may still deny mic / speech
permission at call time even when this returns true.startSpeechRecognition
public void startSpeechRecognition(RecognitionOptions options, RecognitionCallback callback)SpeechRecognizer.recognize for the
callable surface; this hook is the direct delegation point
that platform ports override.stopSpeechRecognition
public void stopSpeechRecognition()isTextToSpeechSupported
public boolean isTextToSpeechSupported()TextToSpeech is implemented on
the current platform.textToSpeechSpeak
public void textToSpeechSpeak(String text, TtsOptions options)textToSpeechStop
public void textToSpeechStop()textToSpeechAvailableVoices
public String[] textToSpeechAvailableVoices()getImageIO
public ImageIO getImageIO()Returns
getVideoIO
public VideoIO getVideoIO()com.codename1.media.VideoIO.Returns
getMediaRecorderingMimeType
public String getMediaRecorderingMimeType()Returns
openOrCreate
public Database openOrCreate(String databaseName)
throws IOException#isDatabaseCustomPathSupported()
this method can optionally accept a file path.Parameters
databaseNameString- the name of the database
Returns
Throws
IOException- if database cannot be created
openOrCreate
public Database openOrCreate(String databaseName, DatabaseConfig config)
throws IOExceptionOpens an encrypted database or creates one if it does not exist.
Prefer com.codename1.db.Database#openOrCreate(java.lang.String, com.codename1.db.DatabaseConfig),
which validates the name and the platform’s capability before delegating here.
Parameters
databaseNameString- the name of the database
configDatabaseConfig- how the database should be keyed
Returns
Throws
IOException- if the database cannot be opened, created or decrypted
isDatabaseEncryptionSupported
public boolean isDatabaseEncryptionSupported()Returns
openOrCreateForRekey
public Database openOrCreateForRekey(String databaseName)
throws IOExceptionParameters
databaseNameString- the name of the database
Returns
Throws
IOException- if the database cannot be opened
isDatabaseManagedKeyHardwareBacked
public boolean isDatabaseManagedKeyHardwareBacked()Returns
databaseManagedKeyIdentity
public String databaseManagedKeyIdentity(String databaseName)Parameters
databaseNameString- the name of the database
Returns
one of the CodenameOneImplementation DATABASE_ENCRYPT* constants
The identity a managed database key with no explicit alias is stored under.
See com.codename1.impl.CodenameOneImplementation#databaseManagedKeyIdentity(String).
databaseRegistryIdentity
public String databaseRegistryIdentity(String databaseName)com.codename1.impl.CodenameOneImplementation#databaseRegistryIdentity(String).Parameters
databaseNameString- the database, as an application named it
Returns
isRelativeAttachmentNameResolvable
public boolean isRelativeAttachmentNameResolvable()com.codename1.impl.CodenameOneImplementation#isRelativeAttachmentNameResolvable().Returns
databaseIdentityForEngineFile
public String databaseIdentityForEngineFile(String engineFile)com.codename1.impl.CodenameOneImplementation#databaseIdentityForEngineFile(String).Parameters
engineFileString- the filename the engine reported
Returns
openDatabaseConnections
public int openDatabaseConnections(String databaseName)com.codename1.impl.CodenameOneImplementation#openDatabaseConnections(String).Parameters
databaseNameString- the name or path being deleted
Returns
isDatabaseFileEncrypted
public int isDatabaseFileEncrypted(String databaseName)isBlobQueryParameterSupported
public boolean isBlobQueryParameterSupported()byte[] values may be used as query parameters.Returns
isDatabaseCustomPathSupported
public boolean isDatabaseCustomPathSupported()Returns
delete
public void delete(String databaseName)
throws IOExceptionParameters
databaseNameString- the name of the database
Throws
IOException- if database cannot be deleted
exists
public boolean exists(String databaseName)Parameters
databaseNameString- the name of the database
Returns
getDatabasePath
public String getDatabasePath(String databaseName)Parameters
databaseNameString- the name of the database with out / or path
elements e.g.
mydatabase.db
Returns
setPollingFrequency
public void setPollingFrequency(int freq)Parameters
freqint- the frequency in milliseconds
createThread
public Thread createThread(Runnable r, String name)Parameters
rRunnable- runnable to run, NOTICE the thread MUST be explicitly started!
nameString- the name for the thread
Returns
startThread
public Thread startThread(Runnable r, String name)java.lang.String) insteadParameters
rRunnable- runnable to run, NOTICE the thread MUST be explicitly started!
nameString- the name for the thread
Returns
isNativeTitle
public boolean isNativeTitle()Returns
refreshNativeTitle
public void refreshNativeTitle()getCrashReporter
public CrashReport getCrashReporter()Returns
setCrashReporter
public void setCrashReporter(CrashReport crashReporter)Parameters
crashReporterCrashReport- the crashReporter to set
getUdid
public String getUdid()Returns
getMsisdn
public String getMsisdn()Returns
getInAppPurchase
public Purchase getInAppPurchase()Returns
getInAppPurchase
public Purchase getInAppPurchase(boolean d)getCodeScanner
public CodeScanner getCodeScanner()Returns
getAvailableRecordingMimeTypes
public String[] getAvailableRecordingMimeTypes()isScreenSaverDisableSupported
public boolean isScreenSaverDisableSupported()isScrollWheeling
public boolean isScrollWheeling()Returns
setScreenSaverEnabled
public void setScreenSaverEnabled(boolean e)Parameters
eboolean- when set to true the screen saver will work as usual and when set to false the screen will not turn off automatically
hasCamera
public boolean hasCamera()isNativePickerTypeSupported
public boolean isNativePickerTypeSupported(int pickerType)Parameters
pickerTypeint- the picker type constant
Returns
showNativePicker
public Object showNativePicker(int type, Component source, Object currentValue, Object data)Parameters
typeint- the picker type constant
sourceComponent- the source component (optional) the native dialog will be placed in relation to this component if applicable
currentValueObject- the currently selected value
dataObject- additional meta data specific to the picker type when applicable
Returns
isMultiKeyMode
public boolean isMultiKeyMode()Returns
setMultiKeyMode
public void setMultiKeyMode(boolean multiKeyMode)Parameters
multiKeyModeboolean- the multiKeyMode to set
getLongPointerPressInterval
public int getLongPointerPressInterval()Returns
setLongPointerPressInterval
public void setLongPointerPressInterval(int v)Parameters
vint- time in milliseconds
scheduleLocalNotification
public void scheduleLocalNotification(LocalNotification n, long firstTime, int repeat)Schedules a local notification that will occur after the given time elapsed.
The sample below combines this with the geofence API to show a local notification when entering a radius with the app in the background:
// File: GeofenceListenerImpl.java
public class GeofenceListenerImpl implements GeofenceListener {
@Override
public void onExit(String id) {
}
@Override
public void onEntered(String id) {
if(!Display.getInstance().isMinimized()) {
Display.getInstance().callSerially(() -> {
Dialog.show("Welcome", "Thanks for arriving", "OK", null);
});
} else {
LocalNotification ln = new LocalNotification();
ln.setId("LnMessage");
ln.setAlertTitle("Welcome");
ln.setAlertBody("Thanks for arriving!");
Display.getInstance().scheduleLocalNotification(ln, System.currentTimeMillis() + 10, LocalNotification.REPEAT_NONE);
}
}
}
// File: GeofenceSample.java
Geofence gf = new Geofence("test", loc, 100, 100000);
LocationManager.getLocationManager().addGeoFencing(GeofenceListenerImpl.class, gf);
Parameters
nLocalNotification- The notification to schedule.
firstTimelong- time in milliseconds when to schedule the notification
repeatint- repeat one of the following: REPEAT_NONE, REPEAT_FIFTEEN_MINUTES, REPEAT_HALF_HOUR, REPEAT_HOUR, REPEAT_DAY, REPEAT_WEEK
cancelLocalNotification
public void cancelLocalNotification(String notificationId)requestNotificationPermission
public void requestNotificationPermission(NotificationPermissionCallback callback)Parameters
callbackNotificationPermissionCallback- the callback to receive the result
requestNotificationPermission
public void requestNotificationPermission(NotificationPermissionRequest request, NotificationPermissionCallback callback)Parameters
requestNotificationPermissionRequest- describes which notification capabilities to request
callbackNotificationPermissionCallback- the callback to receive the result
registerNotificationChannel
public void registerNotificationChannel(NotificationChannelBuilder builder)Parameters
builderNotificationChannelBuilder- the channel definition
deleteNotificationChannel
public void deleteNotificationChannel(String channelId)Parameters
channelIdString- the channel id to delete
createNotificationChannelGroup
public void createNotificationChannelGroup(String groupId, String groupName)Parameters
groupIdString- the group id
groupNameString- the user-visible group name
scheduleBackgroundWork
public void scheduleBackgroundWork(WorkRequest request)com.codename1.background.BackgroundWork.Parameters
requestWorkRequest- the work request
cancelBackgroundWork
public void cancelBackgroundWork(String workId)Parameters
workIdString- the work id
isBackgroundWorkSupported
public boolean isBackgroundWorkSupported()Returns
scheduleBackgroundProcessing
public void scheduleBackgroundProcessing(String id, long earliestBeginEpochMs, boolean requiresNetwork, boolean requiresPower, Runnable task)com.codename1.background.BackgroundTask.Parameters
idString- the task id
earliestBeginEpochMslong- the earliest begin time in milliseconds since the epoch, or 0
requiresNetworkboolean- true if network is required
requiresPowerboolean- true if charging is required
taskRunnable- the work to run
cancelBackgroundProcessing
public void cancelBackgroundProcessing(String id)Parameters
idString- the task id
isBackgroundProcessingSupported
public boolean isBackgroundProcessingSupported()Returns
startForegroundService
public Object startForegroundService(String channelId, String title, String body, String iconName, ForegroundService.Task task, ForegroundService handle)com.codename1.background.ForegroundService.Parameters
channelIdString- the notification channel id
titleString- the notification title
bodyString- the notification body
iconNameString- the small icon resource name, or null
taskForegroundService.Task- the task to run
handleForegroundService- the service handle passed to the task
Returns
updateForegroundServiceNotification
public void updateForegroundServiceNotification(Object nativeHandle, String title, String body)Parameters
nativeHandleObject- the handle returned by
#startForegroundService titleString- the new title
bodyString- the new body
stopForegroundService
public void stopForegroundService(Object nativeHandle)Parameters
nativeHandleObject- the handle returned by
#startForegroundService
isForegroundServiceSupported
public boolean isForegroundServiceSupported()Returns
isWalletExtensionSupported
public boolean isWalletExtensionSupported()com.codename1.payment.WalletExtension.walletExtensionSetPassEntries
public void walletExtensionSetPassEntries(boolean remote, WalletPassEntry[] entries)com.codename1.payment.WalletExtension.Parameters
remoteboolean- true for the Apple Watch list, false for the iPhone list
entriesWalletPassEntry[]- the available cards; null or empty clears the list
walletExtensionSetRequiresAuthentication
public void walletExtensionSetRequiresAuthentication(boolean requiresAuthentication)com.codename1.payment.WalletExtension.walletExtensionSetAuthToken
public void walletExtensionSetAuthToken(String token)com.codename1.payment.WalletExtension.walletExtensionClear
public void walletExtensionClear()com.codename1.payment.WalletExtension.subscribeToPushTopic
public void subscribeToPushTopic(String topic)com.codename1.push.Push.Parameters
topicString- the topic name
unsubscribeFromPushTopic
public void unsubscribeFromPushTopic(String topic)com.codename1.push.Push.Parameters
topicString- the topic name
setPreferredBackgroundFetchInterval
public void setPreferredBackgroundFetchInterval(int seconds)Sets the preferred time interval between background fetches. This is only a preferred interval and is not guaranteed. Some platforms, like iOS, maintain sovereign control over when and if background fetches will be allowed. This number is used only as a guideline.
This method must be called in order to activate background fetch.>
Note: If the platform doesn’t support background fetch (i.e. #isBackgroundFetchSupported() returns false,
then this method does nothing.
Parameters
secondsint- The time interval in seconds.
getPreferredBackgroundFetchInterval
public int getPreferredBackgroundFetchInterval(int seconds)Returns
isBackgroundFetchSupported
public boolean isBackgroundFetchSupported()Returns
isSimulator
public boolean isSimulator()Returns
isDebuggableBuild
public boolean isDebuggableBuild()Whether this build is a development build rather than a release build headed for
an app store. This is broader than isSimulator(), which reports the JavaSE
simulator and designer specifically and is false on a device however the build was
signed. Use it to gate a facility that belongs in a build you are working on but
not in one a user installs.
What each port reports:
Android: true when the package carries the debuggable flag, which a debug build sets and a release build clears.
iOS: true when the provisioning profile grants get-task-allow, the entitlement that permits a debugger to attach. Development and ad-hoc profiles carry it; App Store and enterprise profiles do not.
JavaSE: ALWAYS true. That port runs the simulator, the designer and the desktop tooling, and it cannot distinguish those from a desktop application packaged for distribution, so a packaged desktop app also reports true. Do not rely on this method alone to withhold something from a shipped DESKTOP build; combine it with your own signal there.
Any other port: false, because it cannot tell. The answer errs towards treating a build as a release and withholding the facility.
Returns
createBackgroundMedia
public Media createBackgroundMedia(String uri)
throws IOExceptionParameters
uriString- the uri of the media can start with jar://, file://, http:// (can also use rtsp:// if supported on the platform)
Returns
Throws
IOException- if creation of media from the given URI has failed
createBackgroundMediaAsync
public AsyncResource<Media> createBackgroundMediaAsync(String uri)Parameters
uriString- the uri of the media can start with jar://, file://, http:// (can also use rtsp:// if supported on the platform)
Returns
gaussianBlurImage
public Image gaussianBlurImage(Image image, float radius)Parameters
imageImage- the image to blur
radiusfloat- the radius to be used in the algorithm
createSFSymbolImage
public Image createSFSymbolImage(String name, int color, float sizePixels, int weight)isGaussianBlurSupported
public boolean isGaussianBlurSupported()Returns
refreshContacts
public void refreshContacts()com.codename1.contacts.ContactsManager#refresh()isJailbrokenDevice
public boolean isJailbrokenDevice()Returns
requestIntegrityToken
public AsyncResource<String> requestIntegrityToken(String nonce)com.codename1.security.DeviceIntegrity#requestIntegrityToken(String).isAttestationSupported
public boolean isAttestationSupported()isDeviceCompromised
public boolean isDeviceCompromised()getCompromiseReasons
public String[] getCompromiseReasons()isDeviceCompromised() (e.g. “root”, “frida”, “emulator”).getEnabledAccessibilityServices
public String[] getEnabledAccessibilityServices()resetAttestation
public void resetAttestation()com.codename1.security.DeviceIntegrity#resetAttestation().confirmAttestation
public void confirmAttestation(String keyId)com.codename1.security.DeviceIntegrity#confirmAttestation().getAppSignerDigests
public String[] getAppSignerDigests()setSecureScreen
public void setSecureScreen(boolean secure)FLAG_SECURE), blocking screenshots/recording/scraping.setTapjackingProtection
public void setTapjackingProtection(TapjackingPolicy policy)com.codename1.security.DeviceIntegrity#setTapjackingProtection(TapjackingPolicy).getTapjackingPolicy
public TapjackingPolicy getTapjackingPolicy()isScreenObscured
public boolean isScreenObscured()com.codename1.security.DeviceIntegrity#isScreenObscured().addTapjackingListener
public void addTapjackingListener(ActionListener l)removeTapjackingListener
public void removeTapjackingListener(ActionListener l)addTapjackingListener().setHideOverlayWindows
public void setHideOverlayWindows(boolean hide)isHideOverlayWindowsSupported
public boolean isHideOverlayWindowsSupported()setHideOverlayWindows() is actually enforced by the platform.getProjectBuildHints
public Map<String, String> getProjectBuildHints()Returns
setProjectBuildHint
public void setProjectBuildHint(String key, String value)Parameters
keyString- the build hint without the codename1.arg. prefix
valueString- the value for the hint
canInstallOnHomescreen
public boolean canInstallOnHomescreen()Checks to see if you can prompt the user to install the app on their homescreen. This is only relevant for the Javascript port with PWAs. This is not a “static” property, as it only returns true if the app is in a state that allows you to prompt the user. E.g. if you have previously prompted the user and they have declined, then this will return false.
Best practice is to use #onCanInstallOnHomescreen(java.lang.Runnable) to be notified
when you are allowed to prompt the user for installation. Then call #promptInstallOnHomescreen()
inside that method - or sometime after.
Example
`onCanInstallOnHomescreen(()->{
if (canInstallOnHomescreen()) {
if (promptInstallOnHomescreen()) {
// User accepted installation` else {
// user rejected installation
}
}
});
}
https://developers.google.com/web/fundamentals/app-install-banners/
Returns
promptInstallOnHomescreen
public boolean promptInstallOnHomescreen()Returns
onCanInstallOnHomescreen
public void onCanInstallOnHomescreen(Runnable r)Parameters
rRunnable- Runnable that will be run when/if you are permitted to prompt the user to install the app on their homescreen.
captureScreen
public Image captureScreen()Returns
screenshot
public void screenshot(SuccessCallback<Image> callback)Parameters
callbackSuccessCallback<Image>- will be invoked on the EDT with a screenshot
notifyPushCompletion
public void notifyPushCompletion()Notifies the platform that push notification processing is complete. This is useful on iOS where the app is woken up in the background to handle a push notification and needs to signal completion to avoid being suspended prematurely.
If the ios.delayPushCompletion build hint (or property) is set to “true”,
Codename One will NOT automatically signal completion after the com.codename1.push.PushCallback#push(String)
method returns. Instead, the application MUST invoke this method manually
when it has finished its background work (e.g. playing audio, downloading content).
setTimeout
public Timer setTimeout(int timeout, Runnable r)Parameters
timeoutint- The timeout in milliseconds.
rRunnable- The task to run.
Returns
setInterval
public Timer setInterval(int period, Runnable r)Parameters
periodint- The delay and repeat in milliseconds.
rRunnable- The runnable to run on the EDT.
Returns
firePinchBeginGesture
public void firePinchBeginGesture()Starts a magnify (pinch) gesture. Invoked by the implementation when the platform reports that a gesture began, before any scale is delivered.
A port that reports this gets the gesture delivered to one component for its whole duration; one that does not keeps the older behaviour of resolving the component from the coordinates on every update. Reporting it also discards a claim whose release never arrived, so a cancelled gesture cannot strand the next one.
firePinchReleaseGesture
public void firePinchReleaseGesture(int x, int y)Parameters
xint- the gesture x position in display pixels
yint- the gesture y position in display pixels