public class CN

  1. Object
  2. CN1Constants
  3. CN

Known subtypesFont

This is a global context static class designed for static import, this class allows us to write more terse code. However, its chief purpose is simplification by hiding some of the more esoteric methods of these underlying classes and bringing to the front the commonly used important methods. This class includes code from Display, NetworkManager, Log and other important classes

Fields

public static final String NATIVE_MAIN_THIN = "native:MainThin"Constant for the name of the main thin native font.
public static final String NATIVE_MAIN_LIGHT = "native:MainLight"Constant for the main light native font.
public static final String NATIVE_MAIN_REGULAR = "native:MainRegular"Constant for the main regular native font.
public static final String NATIVE_MAIN_BOLD = "native:MainBold"Constant for the main bold native font.
public static final String NATIVE_MAIN_BLACK = "native:MainBlack"Constant for the main black native font.
public static final String NATIVE_ITALIC_THIN = "native:ItalicThin"Constant for the italic thin native font.
public static final String NATIVE_ITALIC_LIGHT = "native:ItalicLight"Constant for the italic light native font.
public static final String NATIVE_ITALIC_REGULAR = "native:ItalicRegular"Constant for the italic regular native font.
public static final String NATIVE_ITALIC_BOLD = "native:ItalicBold"Constant for the italic bold native font.
public static final String NATIVE_ITALIC_BLACK = "native:ItalicBlack"Constant for the italic black native font.
public static final int FACE_MONOSPACE = 32Constant allowing us to author portable system fonts
public static final int FACE_PROPORTIONAL = 64Constant allowing us to author portable system fonts
public static final int FACE_SYSTEM = 0Constant allowing us to author portable system fonts
public static final int SIZE_LARGE = 16Constant allowing us to author portable system fonts
public static final int SIZE_MEDIUM = 0Constant allowing us to author portable system fonts
public static final int SIZE_SMALL = 8Constant allowing us to author portable system fonts
public static final int STYLE_BOLD = 1Constant allowing us to author portable system fonts
public static final int STYLE_ITALIC = 2Constant allowing us to author portable system fonts
public static final int STYLE_UNDERLINED = 4Constant allowing us to author portable system fonts
public static final int STYLE_PLAIN = 0Constant allowing us to author portable system fonts
public static final String NORTH = "North"The north layout constraint (top of container).
public static final String SOUTH = "South"The south layout constraint (bottom of container).
public static final String WEST = "West"The west layout constraint (left of container).
public static final String EAST = "East"The east layout constraint (right of container).
public static final int CENTER = 4Indicates a Component center alignment
public static final int TOP = 0Box-orientation constant used to specify the top of a box.
public static final int LEFT = 1Box-orientation constant used to specify the left side of a box.
public static final int BOTTOM = 2Box-orientation constant used to specify the bottom of a box.
public static final int RIGHT = 3Box-orientation constant used to specify the right side of a box.
public static final int BASELINE = 5Alignment to the baseline constraint
public static final int CENTER_BEHAVIOR_SCALE = 0Defines the behavior of the component placed in the center position of the layout, by default it is scaled to the available space
public static final int CENTER_BEHAVIOR_CENTER = 1Defines the behavior of the component placed in the center position of the layout, places the component in the center of the space available to the center component.
public static final int CENTER_BEHAVIOR_CENTER_ABSOLUTE = 2Defines the behavior of the component placed in the center position of the layout, places the component in the center of the surrounding container
public static final int CENTER_BEHAVIOR_TOTAL_BELOW = 3The center component takes up the entire screens and the sides are automatically placed on top of it thus creating a layered effect

Methods

public static void setBookmark(Runnable bookmark)Sets a bookmark that can restore the app to a particular state.
public static void restoreToBookmark()Runs the last bookmark that was set using #setBookmark(java.lang.Runnable)
public static int getDragStartPercentage()This method allows us to manipulate the drag started detection logic.
public static void setDragStartPercentage(int dragStartPercentage)This method allows us to manipulate the drag started detection logic.
public static Object createSoftWeakRef(Object o)Creates a soft/weak reference to an object that allows it to be collected yet caches it.
public static Object extractHardRef(Object o)Extracts the hard reference from the soft/weak reference given
public static boolean isEnableAsyncStackTraces()Checks if async stack traces are enabled.
public static void setEnableAsyncStackTraces(boolean enable)Enables or disables async stack traces.
public static 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 static void announceForAccessibility(Component cmp, String text)Manually announces text to native accessibility services, optionally associating the announcement with a specific component.
public static void announceForAccessibility(String text)Convenience overload to announce text without specifying a component.
public static boolean isEdt()Returns true if we are currently in the event dispatch thread.
public static void callSerially(Runnable r)Causes the runnable to be invoked on the event dispatch thread.
public static void callSeriallyOnIdle(Runnable r)Causes the runnable to be invoked on the event dispatch thread when the event dispatch thread is idle.
public static void scheduleBackgroundTask(Runnable r)Allows executing a background task in a separate low priority thread.
public static void callSeriallyAndWait(Runnable r)Identical to callSerially with the added benefit of waiting for the Runnable method to complete.
public static void callSeriallyAndWait(Runnable r, int timeout)Identical to callSerially with the added benefit of waiting for the Runnable method to complete.
public static 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 static void invokeWithoutBlocking(Runnable r)Invokes a Runnable with blocking disabled.
public static <T> T invokeWithoutBlockingWithResultSync(RunnableWithResultSync<T> r)Invokes a RunnableWithResultSync with blocking disabled.
public static boolean minimizeApplication()Minimizes the current application if minimization is supported by the platform (may fail).
public static boolean isMinimized()Indicates whether an application is minimized
public static void restoreMinimizedApplication()Restore the minimized application if minimization is supported by the platform
public static Form getCurrentForm()Return the form currently displayed on the screen or null if no form is currently displayed.
public static TopLevelContainer getCurrentTopLevel()The top level the user is currently working in, which may be a Window.
public static int getDisplayWidth()Return the width of the display
public static int getDisplayHeight()Return the height of the display
public static int convertToPixels(int dipCount, boolean horizontal)Converts the dips count to pixels, dips are roughly 1mm in length.
public static int convertToPixels(float value, byte unitType, boolean horizontal)Converts from specified unit to pixels.
public static int convertToPixels(float value, byte unitType)Converts from specified unit to pixels.
public static int convertToPixels(float dipCount)Converts the dips count to pixels, dips are roughly 1mm in length.
public static InputStream getResourceAsStream(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 static 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 static void removeEdtErrorHandler(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 static void exitApplication()Exits the application…
public static 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 static boolean isExitAndClearTaskSupported()Indicates whether this platform can remove the application from its list of recent tasks on exit.
public static 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 static 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 static 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 static void execute(String url)Executes the given URL on the native platform
public static boolean downloadBytesAsFile(String fileName, byte[] bytes)Offers the given in-memory bytes to the user as a downloadable file, bypassing local storage.
public static 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 static boolean isPortrait()Returns true if the device is currently in portrait mode
public static boolean requestFullScreen()Try to enter full-screen mode if the platform supports it.
public static boolean exitFullScreen()Try to exit full-screen mode if the platform supports it.
public static boolean isInFullScreenMode()Checks if the app is currently running in full-screen mode.
public static boolean isFullScreenSupported()Checks if this platform supports full-screen mode.
public static 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 static 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 static boolean isLockOrientation()Returns true if orientation was locked using #lockOrientation(boolean) and not yet unlocked via #unlockOrientation().
public static void unlockOrientation()This is the reverse method for lock orientation allowing orientation lock to be disabled
public static boolean isTablet()Indicates whether the device is a tablet, notice that this is often a guess
public static boolean isDesktop()Returns true if this is a desktop application
public static boolean isMultiWindowSupported()Indicates whether this platform can open desktop windows, so an application can offer them where they exist and stay on one surface where they do not.
public static boolean isWatch()Indicates whether the application is running on a smartwatch form factor (Apple Watch / Wear OS).
public static boolean isTV()Indicates whether the application is running on a television form factor (Apple TV / Android TV / Google TV).
public static boolean isCarConnected()Indicates whether a head unit (Apple CarPlay / Google Android Auto) is currently connected and projecting the com.codename1.car experience.
public static 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 static int getPointerButton()The mouse button associated with the current pointer event, one of the com.codename1.ui.events.PointerEvent BUTTON_* constants.
public static int getPressedButtonMask()A bitmask of the mouse buttons currently held down, built from the com.codename1.ui.events.PointerEvent MASK_* constants.
public static int getPointerType()The current pointing device type, one of the com.codename1.ui.events.PointerEvent TYPE_* constants (finger, mouse, stylus or eraser).
public static float getPointerPressure()The normalized pressure of the current pointer event between 0.0 and 1.0.
public static float getPointerTiltX()The stylus tilt across the x axis of the current pointer event in degrees, or 0 when not reported.
public static float getPointerTiltY()The stylus tilt across the y axis of the current pointer event in degrees, or 0 when not reported.
public static float getPointerContactSize()The normalized contact size of the current pointer event between 0.0 and 1.0, or 0 when not reported.
public static boolean isStylusPointer()True if the current pointer is a stylus or pen (Apple Pencil, S-Pen and similar).
public static boolean isFoldable()True if the device is a foldable or dual screen device.
public static DevicePosture getDevicePosture()Returns the live device fold posture.
public static void addPostureListener(ActionListener l)Adds a listener that is notified when the device is folded, unfolded or changes posture.
public static void removePostureListener(ActionListener l)Removes a posture listener.
public static 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 static int getDisplayCount()Returns the number of displays (monitors or external screens) currently attached.
public static boolean isExternalDisplayConnected()True if an external or secondary display is currently attached.
public static Dimension getDesktopSize()Returns the size of the desktop hosting the application window when running on a desktop platform.
public static Rectangle getWindowBounds()Returns the number of monitors attached to the desktop environment when available.
public static void setWindowSize(int width, int height)Requests a resize of the application window when supported by the platform.
public static Dimension getInitialWindowSizeHintPercent()Returns the initial desktop window size hint provided by the first shown form, when available.
public static 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 static void addWindowListener(ActionListener<WindowEvent> l)Adds a listener for window events such as resize or move.
public static void removeWindowListener(ActionListener<WindowEvent> l)Removes a previously registered window listener.
public static boolean canDial()Returns true if the device has dialing capabilities
public static Boolean isDarkMode()Returns true if the platform is in dark mode, null is returned for unknown status
public static boolean isHighContrastEnabled()Returns true when the user requests stronger foreground/background contrast.
public static boolean isDifferentiateWithoutColorEnabled()Returns true when the user requests that information isn’t conveyed by color alone.
public static AccessibilityColorVisionDeficiency getColorVisionDeficiency()Returns the selected color-vision correction mode.
public static boolean isReduceMotionEnabled()Returns true when the user requests reduced or disabled nonessential motion.
public static boolean isReduceTransparencyEnabled()Returns true when the user requests reduced transparency and blur effects.
public static boolean isBoldTextEnabled()Returns true when the user requests heavier text weight.
public static boolean isInvertColorsEnabled()Returns true when the operating system is inverting displayed colors.
public static boolean isGrayscaleEnabled()Returns true when the operating system requests a grayscale presentation.
public static boolean isOnOffSwitchLabelsEnabled()Returns true when switches should include visible on/off labels.
public static boolean isScreenReaderEnabled()Returns true when a screen reader or touch-exploration service is active.
public static void setDarkMode(Boolean darkMode)Override the default dark mode setting
public static void openGallery(ActionListener response, int type)Opens the device gallery to pick an image or a video.
public static void openFileChooser(ActionListener response, String accept)Opens a file chooser for arbitrary user-selected files.
public static String getPlatformName()Returns a 2-3 letter code representing the platform name for the platform override
public static Simd getSimd()Returns the SIMD API for the current platform.
public static boolean isGpuSupported()Returns true if the current platform provides a hardware accelerated 3D GPU backend for com.codename1.gpu.RenderView.
public static void dial(String phoneNumber)Opens the device Dialer application with the given phone number
public static 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 static void sendSMS(String phoneNumber, String message) throws IOExceptionSends a SMS message to the given phone number
public static 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.
public static void share(String text, String image, String mimeType)Share the required information using the platform sharing services.
public static boolean isNativeShareSupported()Indicates if the underlying platform supports sharing capabilities
public static boolean isNativeInAppReviewSupported()Indicates whether the platform exposes a native in-app review/rating prompt (the OS-sanctioned “rate this app” sheet).
public static void requestNativeInAppReview(SuccessCallback<Boolean> done)Requests the native in-app review prompt.
public static void share(String text, String image, String mimeType, Rectangle sourceRect)Share the required information using the platform sharing services.
public static void registerPush()Register to receive push notification, invoke this method once (ever) to receive push notifications.
public static void deregisterPush()Stop receiving push notifications to this client application
public static Thread createThread(Runnable r, String name)Start a Codename One thread that supports crash protection and similar Codename One features.
public static Thread startThread(Runnable r, String name)Deprecated Start a Codename One thread that supports crash protection and similar Codename One features.
public static boolean isScreenSaverDisableSupported()Checks if the device supports disabling the screen display from dimming, allowing the developer to keep the screen display on.
public static void setScreenSaverEnabled(boolean e)If isScreenSaverDisableSupported() returns true calling this method will lock the screen display on
public static boolean hasCamera()Returns true if the device has camera false otherwise.
public static 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 static 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 static void log(String s)Prints to the log
public static void log(Throwable s)Prints to the log
public static void sendLog()Sends the log to your email account
public static void sendMessage(String subject, Message msg, String... recipients)Send an email using the platform mail client.
public static boolean isSimulator()Allows detecting development mode so debugging code and special cases can be used to simplify flow
public static void addDefaultHeader(String key, String value)Adds a header to the global default headers, this header will be implicitly added to all requests going out from this point onwards.
public static void addToQueueAndWait(ConnectionRequest request)Identical to add to queue but waits until the request is processed in the queue, this is useful for completely synchronous operations.
public static void addToQueue(ConnectionRequest request)Adds the given network connection to the queue of execution
public static void killAndWait(ConnectionRequest request)Kills the given request and waits until the request is killed if it is being processed by one of the threads.
public static void addNetworkErrorListener(ActionListener<NetworkEvent> e)Adds a generic listener to a network error that is invoked before the exception is propagated.
public static void removeNetworkErrorListener(ActionListener<NetworkEvent> e)Removes the given error listener
public static void addNetworkProgressListener(ActionListener<NetworkEvent> al)Adds a listener to be notified when progress updates
public static void removeNetworkProgressListener(ActionListener<NetworkEvent> al)Adds a listener to be notified when progress updates
public static void updateNetworkThreadCount(int threadCount)Sets the number of network threads and restarts the network threads
public static void clearStorageCache()Storage is cached for faster access, however this might cause a problem with refreshing objects since they are not cloned.
public static void flushStorageCache()Flush the storage cache allowing implementations that cache storage objects to store
public static void deleteStorageFile(String name)Deletes the given file name from the storage
public static void clearStorage()Deletes all the files in the application storage
public static OutputStream createStorageOutputStream(String name) throws IOExceptionCreates an output stream to the storage with the given name
public static InputStream createStorageInputStream(String name) throws IOExceptionCreates an input stream to the given storage source file
public static boolean existsInStorage(String name)Returns true if the given storage file exists
public static String[] listStorageEntries()Lists the names of the storage files
public static int storageEntrySize(String name)Returns the size in bytes of the given entry
public static boolean writeObjectToStorage(String name, Object o)Writes the given object to storage assuming it is an externalizable type or one of the supported types.
public static Object readObjectFromStorage(String name)Reads the object from the storage, returns null if the object isn’t there
public static String[] getFileSystemRoots()Returns the filesystem roots from which the structure of the file system can be traversed
public static int getFileSystemRootType(String root)Returns the type of the root often by guessing
public static String[] listFiles(String directory) throws IOExceptionLists the files within the given directory, returns relative file names and not full file names.
public static long getFileSystemRootSizeBytes(String root)Returns the size of the given root directory
public static long getFileSystemRootAvailableSpace(String root)Returns the available space in the given root directory
public static void mkdir(String directory)Creates the given directory
public static void delete(String file)Deletes the specific file or empty directory.
public static boolean existsInFileSystem(String file)Indicates whether a file exists
public static boolean isHiddenFile(String file)Indicates the hidden state of the file
public static void setHiddenFile(String file, boolean h)Toggles the hidden state of the file
public static void renameFile(String file, String newName)Renames a file to the given name, expects the new name to be relative to the current directory
public static long getFileLength(String file)Returns the length of the file
public static long getFileLastModifiedFile(String file)Deprecated Returns the time that the file denoted by this abstract pathname was last modified.
public static boolean isDirectory(String file)Indicates whether the given file is a directory
public static OutputStream openFileOutputStream(String file) throws IOExceptionOpens an output stream to the given file
public static InputStream openFileInputStream(String file) throws IOExceptionOpens an input stream to the given file
public static OutputStream openFileOutputStream(String file, int offset) throws IOExceptionOpens an output stream to the given file
public static String getAppHomePath()The application home directory is a “safe place” to store files for this application in a portable way.
public static boolean hasCachesDir()Returns true if the device has a directory dedicated for “cache” files
public static String getCachesDir()Returns a device specific directory designed for cache style files, or null if #hasCachesDir() is false
public static boolean canInstallOnHomescreen()Checks to see if you can prompt the user to install the app on their homescreen.
public static boolean promptInstallOnHomescreen()Prompts the user to install this app on their homescreen.
public static void onCanInstallOnHomescreen(Runnable r)A callback fired when you are allowed to prompt the user to install the app on their homescreen.
public static Image captureScreen()Captures a screenshot of the screen.
public static void addMessageListener(ActionListener<MessageEvent> l)Adds a listener to receive messages from the native platform.
public static void removeMessageListener(ActionListener<MessageEvent> l)Removes a listener from receiving messages from the native platform.
public static void postMessage(MessageEvent message)Posts a message to the native platform.
public static Timer setTimeout(int timeout, Runnable r)Convenience method to schedule a task to run on the EDT after timeoutms.
public static Timer setInterval(int timeout, Runnable r)Convenience method to schedule a task to run on the EDT after periodms repeating every periodms.
public static BrowserComponent getSharedJavascriptContext()Gets a reference to an application-wide shared Javascript context that can be used for running Javascript commands.
public static PluginSupport getPluginSupport()Returns the plugin support object for the current platform.

Inherited fields

Inherited methods

Field details

NATIVE_MAIN_THIN

public static final String NATIVE_MAIN_THIN = "native:MainThin"
Constant for the name of the main thin native font.

NATIVE_MAIN_LIGHT

public static final String NATIVE_MAIN_LIGHT = "native:MainLight"
Constant for the main light native font.

NATIVE_MAIN_REGULAR

public static final String NATIVE_MAIN_REGULAR = "native:MainRegular"
Constant for the main regular native font.

NATIVE_MAIN_BOLD

public static final String NATIVE_MAIN_BOLD = "native:MainBold"
Constant for the main bold native font.

NATIVE_MAIN_BLACK

public static final String NATIVE_MAIN_BLACK = "native:MainBlack"
Constant for the main black native font.

NATIVE_ITALIC_THIN

public static final String NATIVE_ITALIC_THIN = "native:ItalicThin"
Constant for the italic thin native font.

NATIVE_ITALIC_LIGHT

public static final String NATIVE_ITALIC_LIGHT = "native:ItalicLight"
Constant for the italic light native font.

NATIVE_ITALIC_REGULAR

public static final String NATIVE_ITALIC_REGULAR = "native:ItalicRegular"
Constant for the italic regular native font.

NATIVE_ITALIC_BOLD

public static final String NATIVE_ITALIC_BOLD = "native:ItalicBold"
Constant for the italic bold native font.

NATIVE_ITALIC_BLACK

public static final String NATIVE_ITALIC_BLACK = "native:ItalicBlack"
Constant for the italic black native font.

FACE_MONOSPACE

public static final int FACE_MONOSPACE = 32
Constant allowing us to author portable system fonts

FACE_PROPORTIONAL

public static final int FACE_PROPORTIONAL = 64
Constant allowing us to author portable system fonts

FACE_SYSTEM

public static final int FACE_SYSTEM = 0
Constant allowing us to author portable system fonts

SIZE_LARGE

public static final int SIZE_LARGE = 16
Constant allowing us to author portable system fonts

SIZE_MEDIUM

public static final int SIZE_MEDIUM = 0
Constant allowing us to author portable system fonts

SIZE_SMALL

public static final int SIZE_SMALL = 8
Constant allowing us to author portable system fonts

STYLE_BOLD

public static final int STYLE_BOLD = 1
Constant allowing us to author portable system fonts

STYLE_ITALIC

public static final int STYLE_ITALIC = 2
Constant allowing us to author portable system fonts

STYLE_UNDERLINED

public static final int STYLE_UNDERLINED = 4
Constant allowing us to author portable system fonts

STYLE_PLAIN

public static final int STYLE_PLAIN = 0
Constant allowing us to author portable system fonts

NORTH

public static final String NORTH = "North"
The north layout constraint (top of container).

SOUTH

public static final String SOUTH = "South"
The south layout constraint (bottom of container).

WEST

public static final String WEST = "West"
The west layout constraint (left of container).

EAST

public static final String EAST = "East"
The east layout constraint (right of container).

CENTER

public static final int CENTER = 4
Indicates a Component center alignment

TOP

public static final int TOP = 0
Box-orientation constant used to specify the top of a box.

LEFT

public static final int LEFT = 1
Box-orientation constant used to specify the left side of a box.

BOTTOM

public static final int BOTTOM = 2
Box-orientation constant used to specify the bottom of a box.

BASELINE

public static final int BASELINE = 5
Alignment to the baseline constraint

CENTER_BEHAVIOR_SCALE

public static final int CENTER_BEHAVIOR_SCALE = 0
Defines the behavior of the component placed in the center position of the layout, by default it is scaled to the available space

CENTER_BEHAVIOR_CENTER

public static final int CENTER_BEHAVIOR_CENTER = 1
Defines the behavior of the component placed in the center position of the layout, places the component in the center of the space available to the center component.

CENTER_BEHAVIOR_CENTER_ABSOLUTE

public static final int CENTER_BEHAVIOR_CENTER_ABSOLUTE = 2
Defines the behavior of the component placed in the center position of the layout, places the component in the center of the surrounding container

CENTER_BEHAVIOR_TOTAL_BELOW

public static final int CENTER_BEHAVIOR_TOTAL_BELOW = 3
The center component takes up the entire screens and the sides are automatically placed on top of it thus creating a layered effect

Method details

setBookmark

public static 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

bookmark Runnable
A Runnable that can be run to restore the app to a particular point.

restoreToBookmark

public static void restoreToBookmark()
Runs the last bookmark that was set using #setBookmark(java.lang.Runnable)

getDragStartPercentage

public static int getDragStartPercentage()
This method allows us to manipulate the drag started detection logic. If the pointer was dragged for more than this percentage of the display size it is safe to assume that a drag is in progress.

Returns

motion percentage

setDragStartPercentage

public static void setDragStartPercentage(int dragStartPercentage)
This method allows us to manipulate the drag started detection logic. If the pointer was dragged for more than this percentage of the display size it is safe to assume that a drag is in progress.

Parameters

dragStartPercentage int
percentage of the screen required to initiate drag

createSoftWeakRef

public static Object createSoftWeakRef(Object o)
Creates a soft/weak reference to an object that allows it to be collected yet caches it. This method is in the porting layer since CLDC only includes weak references while some platforms include nothing at all and some include the superior soft references.

Parameters

o Object
object to cache

Returns

a caching object or null if caching isn’t supported

extractHardRef

public static Object extractHardRef(Object o)
Extracts the hard reference from the soft/weak reference given

Parameters

o Object
the reference returned by createSoftWeakRef

Returns

the original object submitted or null

isEnableAsyncStackTraces

public static 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

Whether async stack traces are enabled.

setEnableAsyncStackTraces

public static void setEnableAsyncStackTraces(boolean enable)

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

enable boolean
True to enable async stack traces.

vibrate

public static 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

Parameters

duration int
length of time to vibrate (might be ignored)

announceForAccessibility

public static void announceForAccessibility(Component cmp, String text)
Manually announces text to native accessibility services, optionally associating the announcement with a specific component. Normally, components are announced automatically when they receive focus; this method is for cases where an announcement is needed outside the normal focus lifecycle.

Parameters

cmp Component
the component related to this announcement or null for the root view
text String
the message to announce

announceForAccessibility

public static void announceForAccessibility(String text)
Convenience overload to announce text without specifying a component.

Parameters

text String
the message to announce

isEdt

public static boolean isEdt()
Returns true if we are currently in the event dispatch thread. This is useful for generic code that can be used both with the EDT and outside of it.

Returns

true if we are currently in the event dispatch thread; otherwise false

callSerially

public static void callSerially(Runnable r)
Causes the runnable to be invoked on the event dispatch thread. This method returns immediately and will not wait for the serial call to occur

Parameters

r Runnable
runnable (NOT A THREAD!) that will be invoked on the EDT serial to the paint and key handling events

callSeriallyOnIdle

public static void callSeriallyOnIdle(Runnable r)
Causes the runnable to be invoked on the event dispatch thread when the event dispatch thread is idle. This method returns immediately and will not wait for the serial call to occur. Notice this method is identical to call serially but will perform the runnable only when the EDT is idle

Parameters

r Runnable
runnable (NOT A THREAD!) that will be invoked on the EDT serial to the paint and key handling events

scheduleBackgroundTask

public static void scheduleBackgroundTask(Runnable r)
Allows executing a background task in a separate low priority thread. Tasks are serialized so they don’t overload the CPU.

Parameters

r Runnable
the task to perform in the background

callSeriallyAndWait

public static void callSeriallyAndWait(Runnable r)
Identical to callSerially with the added benefit of waiting for the Runnable method to complete.

Parameters

r Runnable
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).

callSeriallyAndWait

public static void callSeriallyAndWait(Runnable r, int timeout)
Identical to callSerially with the added benefit of waiting for the Runnable method to complete.

Parameters

r Runnable
runnable (NOT A THREAD!) that will be invoked on the EDT serial to the paint and key handling events
timeout int
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).

invokeAndBlock

public static 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

r Runnable
runnable (NOT A THREAD!) that will be invoked synchroniously by this method

invokeWithoutBlocking

public static void invokeWithoutBlocking(Runnable r)
Invokes a Runnable with blocking disabled. If any attempt is made to block (i.e. call #invokeAndBlock(java.lang.Runnable) from inside this Runnable, it will result in a BlockingDisallowedException being thrown.

Parameters

r Runnable
Runnable to be run immediately.

Throws

BlockingDisallowedException
If #invokeAndBlock(java.lang.Runnable) is attempted anywhere in the Runnable.

invokeWithoutBlockingWithResultSync

public static <T> T invokeWithoutBlockingWithResultSync(RunnableWithResultSync<T> r)
Invokes a RunnableWithResultSync with blocking disabled. If any attempt is made to block (i.e. call #invokeAndBlock(java.lang.Runnable) from inside this Runnable, it will result in a BlockingDisallowedException being thrown.

Parameters

r RunnableWithResultSync<T>
Runnable to be run immediately.

Throws

BlockingDisallowedException
If #invokeAndBlock(java.lang.Runnable) is attempted anywhere in the Runnable.

minimizeApplication

public static boolean minimizeApplication()
Minimizes the current application if minimization is supported by the platform (may fail). Returns false if minimization failed.

Returns

false if minimization failed true if it succeeded or seems to be successful

isMinimized

public static boolean isMinimized()
Indicates whether an application is minimized

Returns

true if the application is minimized

restoreMinimizedApplication

public static void restoreMinimizedApplication()
Restore the minimized application if minimization is supported by the platform

getCurrentForm

public static Form getCurrentForm()
Return the form currently displayed on the screen or null if no form is currently displayed.

Returns

the form currently displayed on the screen or null if no form is currently displayed

getCurrentTopLevel

public static TopLevelContainer getCurrentTopLevel()

The top level the user is currently working in, which may be a Window.

#getCurrentForm() only ever names a Form, so on the desktop it reports the main surface even while the user is looking at another window.

Returns

the focused window when one has focus, otherwise the current form, or null

getDisplayWidth

public static int getDisplayWidth()
Return the width of the display

Returns

the width of the display

getDisplayHeight

public static int getDisplayHeight()
Return the height of the display

Returns

the height of the display

convertToPixels

public static int convertToPixels(int dipCount, boolean horizontal)
Converts the dips count to pixels, dips are roughly 1mm in length. This is a very rough estimate and not to be relied upon

Parameters

dipCount int
the dips that we will convert to pixels
horizontal boolean
indicates pixels in the horizontal plane

Returns

value in pixels

convertToPixels

public static int convertToPixels(float value, byte unitType, boolean horizontal)
Converts from specified unit to pixels.

Parameters

value float
The value to convert, expressed in unitType.
unitType byte
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
horizontal boolean
Whether screen percentage units should be based on horitonzal or vertical percentage.

Returns

The value converted to pixels.

convertToPixels

public static int convertToPixels(float value, byte unitType)
Converts from specified unit to pixels.

Parameters

value float
The value to convert, expressed in unitType.
unitType byte
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

The value converted to pixels.

convertToPixels

public static int convertToPixels(float dipCount)
Converts the dips count to pixels, dips are roughly 1mm in length. This is a very rough estimate and not to be relied upon. This version of the method assumes square pixels which is pretty much the norm.

Parameters

dipCount float
the dips that we will convert to pixels

Returns

value in pixels

getResourceAsStream

public static InputStream getResourceAsStream(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.

Parameters

resource String
relative/absolute URL based on the Java convention

Returns

input stream for the resource or null if not found

addEdtErrorHandler

public static 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

Parameters

e ActionListener
listener receiving the errors

removeEdtErrorHandler

public static void removeEdtErrorHandler(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

Parameters

e ActionListener
listener receiving the errors

exitApplication

public static void exitApplication()
Exits the application…

exitAndClearTask

public static 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. This maps to Android’s 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 static boolean isExitAndClearTaskSupported()
Indicates whether this platform can remove the application from its list of recent tasks on exit. When this returns false #exitAndClearTask() is still legal, it just behaves exactly like #exitApplication().

Returns

true if the task can be cleared, false if the call degrades to a plain exit

getProperty

public static 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

key String
the key of the property
defaultValue String
a default return value

Returns

the value of the property

setProperty

public static 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.

Parameters

key String
key the key of the property
value String
the value of the property

canExecute

public static 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

url String
the url that would be executed

Returns

true if executing this URL should work, returns false if it will not and null if this is unknown

execute

public static 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 JavaScript port this can open a new tab, navigate the current page or show a confirmation Sheet, depending on the javascript.execute.target property. See Display.execute(String) for the details.

Parameters

url String
the url to execute

downloadBytesAsFile

public static boolean downloadBytesAsFile(String fileName, byte[] bytes)
Offers the given in-memory bytes to the user as a downloadable file, bypassing local storage. This exists for platforms (currently the JavaScript port) where the storage-backed 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

fileName String
the suggested file name for the download
bytes byte[]
the file contents

getDeviceDensity

public static 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.

Returns

one of the DENSITY constants of Display

isPortrait

public static boolean isPortrait()
Returns true if the device is currently in portrait mode

Returns

true if the device is in portrait mode

requestFullScreen

public static 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

true on success. This will also return true if the app is already running in full-screen mode. It will return false if the app fails to enter full-screen mode.

exitFullScreen

public static 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

true on success. This will also return true if the app is already NOT in full-screen mode. It will return false if the app fails to exit full-screen mode.

isInFullScreenMode

public static boolean isInFullScreenMode()
Checks if the app is currently running in full-screen mode.

Returns

true if the app is currently in full-screen mode.

isFullScreenSupported

public static 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

true if Full-screen mode is supported on this platform.

canForceOrientation

public static 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

Returns

true if lockOrientation would work

lockOrientation

public static void lockOrientation(boolean portrait)
On devices that return true for canForceOrientation() this method can lock the device orientation either to portrait or landscape mode

Parameters

portrait boolean
true to lock to portrait mode, false to lock to landscape mode

isLockOrientation

public static boolean isLockOrientation()
Returns true if orientation was locked using #lockOrientation(boolean) and not yet unlocked via #unlockOrientation().

Returns

true if orientation is currently marked as locked

unlockOrientation

public static void unlockOrientation()
This is the reverse method for lock orientation allowing orientation lock to be disabled

isTablet

public static boolean isTablet()
Indicates whether the device is a tablet, notice that this is often a guess

Returns

true if the device is assumed to be a tablet

isDesktop

public static boolean isDesktop()
Returns true if this is a desktop application

Returns

true if this is a desktop application

isMultiWindowSupported

public static boolean isMultiWindowSupported()

Indicates whether this platform can open desktop windows, so an application can offer them where they exist and stay on one surface where they do not.

Shorthand for Desktop#isSupported(), kept here because this is where an application already asks what the platform can do. Constructing a com.codename1.ui.Window on a platform that answers false throws rather than quietly degrading to a Form, so this is the guard to branch on.

Returns

true if this platform supports com.codename1.ui.Window

isWatch

public static boolean isWatch()
Indicates whether the application is running on a smartwatch form factor (Apple Watch / Wear OS). Notice that this is often a guess derived from the device metadata.

Returns

true if the device is assumed to be a smartwatch

isTV

public static boolean isTV()
Indicates whether the application is running on a television form factor (Apple TV / Android TV / Google TV). Notice that this is often a guess derived from the device metadata.

Returns

true if the device is assumed to be a TV

isCarConnected

public static boolean isCarConnected()
Indicates whether a head unit (Apple CarPlay / Google Android Auto) is currently connected and projecting the com.codename1.car experience.

Returns

true if a car is connected

getCurrentPointerEvent

public static 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.

Returns

the current com.codename1.ui.events.PointerEvent, never null

getPointerButton

public static int getPointerButton()
The mouse button associated with the current pointer event, one of the com.codename1.ui.events.PointerEvent BUTTON_* constants.

getPressedButtonMask

public static int getPressedButtonMask()
A bitmask of the mouse buttons currently held down, built from the com.codename1.ui.events.PointerEvent MASK_* constants.

getPointerType

public static int getPointerType()
The current pointing device type, one of the com.codename1.ui.events.PointerEvent TYPE_* constants (finger, mouse, stylus or eraser).

getPointerPressure

public static float getPointerPressure()
The normalized pressure of the current pointer event between 0.0 and 1.0. Devices and ports that do not report pressure return 1.0.

getPointerTiltX

public static float getPointerTiltX()
The stylus tilt across the x axis of the current pointer event in degrees, or 0 when not reported.

getPointerTiltY

public static float getPointerTiltY()
The stylus tilt across the y axis of the current pointer event in degrees, or 0 when not reported.

getPointerContactSize

public static float getPointerContactSize()
The normalized contact size of the current pointer event between 0.0 and 1.0, or 0 when not reported.

isStylusPointer

public static boolean isStylusPointer()
True if the current pointer is a stylus or pen (Apple Pencil, S-Pen and similar).

isFoldable

public static boolean isFoldable()
True if the device is a foldable or dual screen device.

getDevicePosture

public static DevicePosture getDevicePosture()
Returns the live device fold posture. See com.codename1.ui.DevicePosture.

addPostureListener

public static void addPostureListener(ActionListener l)
Adds a listener that is notified when the device is folded, unfolded or changes posture.

Parameters

l ActionListener
the listener to add

removePostureListener

public static void removePostureListener(ActionListener l)
Removes a posture listener.

Parameters

l ActionListener
the listener to remove

isDesktopMode

public static 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.

getDisplayCount

public static int getDisplayCount()
Returns the number of displays (monitors or external screens) currently attached.

isExternalDisplayConnected

public static boolean isExternalDisplayConnected()
True if an external or secondary display is currently attached.

getDesktopSize

public static Dimension getDesktopSize()
Returns the size of the desktop hosting the application window when running on a desktop platform.

Returns

the desktop size

getWindowBounds

public static Rectangle getWindowBounds()
Returns the number of monitors attached to the desktop environment when available.

Returns

the number of monitors Returns the current bounds of the application window when supported by the platform.

setWindowSize

public static void setWindowSize(int width, int height)
Requests a resize of the application window when supported by the platform.

Parameters

width int
the desired window width
height int
the desired window height

getInitialWindowSizeHintPercent

public static Dimension getInitialWindowSizeHintPercent()
Returns the initial desktop window size hint provided by the first shown form, when available.

Returns

the stored hint or null

setInitialWindowSizeHintPercent

public static 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. This is primarily useful for desktop environments where the Codename One application is hosted in a window rather than full-screen.

Parameters

hint Dimension
a Dimension whose width/height represent percentages of the desktop to use for the initial window size, or null to clear a previously stored hint

addWindowListener

public static void addWindowListener(ActionListener<WindowEvent> l)
Adds a listener for window events such as resize or move.

Parameters

l ActionListener<WindowEvent>
the listener to add

removeWindowListener

public static void removeWindowListener(ActionListener<WindowEvent> l)
Removes a previously registered window listener.

Parameters

l ActionListener<WindowEvent>
the listener to remove

canDial

public static boolean canDial()
Returns true if the device has dialing capabilities

Returns

false if it cannot dial

isDarkMode

public static Boolean isDarkMode()
Returns true if the platform is in dark mode, null is returned for unknown status

Returns

true in case of dark mode

isHighContrastEnabled

public static boolean isHighContrastEnabled()
Returns true when the user requests stronger foreground/background contrast.

isDifferentiateWithoutColorEnabled

public static boolean isDifferentiateWithoutColorEnabled()
Returns true when the user requests that information isn’t conveyed by color alone.

getColorVisionDeficiency

public static AccessibilityColorVisionDeficiency getColorVisionDeficiency()
Returns the selected color-vision correction mode.

isReduceMotionEnabled

public static boolean isReduceMotionEnabled()
Returns true when the user requests reduced or disabled nonessential motion.

isReduceTransparencyEnabled

public static boolean isReduceTransparencyEnabled()
Returns true when the user requests reduced transparency and blur effects.

isBoldTextEnabled

public static boolean isBoldTextEnabled()
Returns true when the user requests heavier text weight.

isInvertColorsEnabled

public static boolean isInvertColorsEnabled()
Returns true when the operating system is inverting displayed colors.

isGrayscaleEnabled

public static boolean isGrayscaleEnabled()
Returns true when the operating system requests a grayscale presentation.

isOnOffSwitchLabelsEnabled

public static boolean isOnOffSwitchLabelsEnabled()
Returns true when switches should include visible on/off labels.

isScreenReaderEnabled

public static boolean isScreenReaderEnabled()
Returns true when a screen reader or touch-exploration service is active.

setDarkMode

public static void setDarkMode(Boolean darkMode)
Override the default dark mode setting

Parameters

darkMode Boolean
can be set to null to reset to platform default

openGallery

public static 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();

Parameters

response ActionListener
a callback Object to retrieve the file path
type int
one of the following #GALLERY_IMAGE, #GALLERY_VIDEO, #GALLERY_ALL

Throws

RuntimeException
if this feature failed or unsupported on the platform

openFileChooser

public static void openFileChooser(ActionListener response, String accept)

Opens a file chooser for arbitrary user-selected files.

The callback source is a String path readable by FileSystemStorage.openInputStream(), or null if cancelled. accept is a comma-separated list of extensions or MIME types.

Parameters

response ActionListener
callback receiving the selected file path
accept String
comma-separated extensions or MIME types, or null for all files

getPlatformName

public static String getPlatformName()
Returns a 2-3 letter code representing the platform name for the platform override

Returns

the name of the platform e.g. ios, rim, win, and, me, HTML5

getSimd

public static Simd getSimd()
Returns the SIMD API for the current platform.

isGpuSupported

public static boolean isGpuSupported()
Returns true if the current platform provides a hardware accelerated 3D GPU backend for com.codename1.gpu.RenderView.

dial

public static void dial(String phoneNumber)
Opens the device Dialer application with the given phone number

getSMSSupport

public static 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

one of the SMS_* values

sendSMS

public static void sendSMS(String phoneNumber, String message) throws IOException
Sends a SMS message to the given phone number

Parameters

phoneNumber String
to send the sms
message String
the content of the sms

sendSMS

public static 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.

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

phoneNumber String
to send the sms
message String
the content of the sms
interactive boolean
indicates the SMS should show a UI or should not show a UI if applicable see getSMSSupport

share

public static void share(String text, String image, String mimeType)

Share the required information using the platform sharing services. a Sharing service can be: mail, sms, facebook, twitter,… This method is implemented if isNativeShareSupported() returned true for a specific platform.

Since 6.0, there is native sharing support in the Javascript port using the navigator.share API. Currently (2019) this is only supported on Chrome for Android, and will only work if the app is accessed over https:.

Parameters

text String
String to share.
image String
file path to the image or null
mimeType String
type of the image or null if no image to share

isNativeShareSupported

public static boolean isNativeShareSupported()

Indicates if the underlying platform supports sharing capabilities

Since 6.0, there is native sharing support in the Javascript port using the navigator.share API. Currently (2019) this is only supported on Chrome for Android, and will only work if the app is accessed over https:.

Returns

true if the underlying platform handles share.

isNativeInAppReviewSupported

public static boolean isNativeInAppReviewSupported()
Indicates whether the platform exposes a native in-app review/rating prompt (the OS-sanctioned “rate this app” sheet). When false the AppReview API falls back to a Codename One drawn rating widget.

Returns

true if the platform can present a native review prompt.

requestNativeInAppReview

public static void requestNativeInAppReview(SuccessCallback<Boolean> done)
Requests the native in-app review prompt. Should only be invoked when 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

done SuccessCallback<Boolean>
invoked with true once the native prompt was requested or false when the platform did not handle it. May be null.

share

public static void share(String text, String image, String mimeType, Rectangle sourceRect)
Share the required information using the platform sharing services. a Sharing service can be: mail, sms, facebook, twitter,… This method is implemented if isNativeShareSupported() returned true for a specific platform.

Parameters

text String
String to share.
image String
file path to the image or null
mimeType String
type of the image or null if no image to share
sourceRect Rectangle
The source rectangle of the button that originated the share request. This is used on some platforms to provide a hint as to where the share dialog overlay should pop up. Particularly, on the iPad with iOS 8 and higher.

registerPush

public static void registerPush()
Register to receive push notification, invoke this method once (ever) to receive push notifications.

deregisterPush

public static void deregisterPush()
Stop receiving push notifications to this client application

createThread

public static Thread createThread(Runnable r, String name)
Start a Codename One thread that supports crash protection and similar Codename One features.

Parameters

r Runnable
runnable to run, NOTICE the thread MUST be explicitly started!
name String
the name for the thread

Returns

a thread instance which must be explicitly started!

startThread

public static Thread startThread(Runnable r, String name)
Deprecated. confusing name, use java.lang.String) instead
Start a Codename One thread that supports crash protection and similar Codename One features.

Parameters

r Runnable
runnable to run, NOTICE the thread MUST be explicitly started!
name String
the name for the thread

Returns

a thread instance which must be explicitly started!

isScreenSaverDisableSupported

public static boolean isScreenSaverDisableSupported()
Checks if the device supports disabling the screen display from dimming, allowing the developer to keep the screen display on.

setScreenSaverEnabled

public static void setScreenSaverEnabled(boolean e)
If isScreenSaverDisableSupported() returns true calling this method will lock the screen display on

Parameters

e boolean
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 static boolean hasCamera()
Returns true if the device has camera false otherwise.

isNativePickerTypeSupported

public static 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

Parameters

pickerType int
the picker type constant

Returns

true if the native platform supports this picker type

showNativePicker

public static 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

Parameters

type int
the picker type constant
source Component
the source component (optional) the native dialog will be placed in relation to this component if applicable
currentValue Object
the currently selected value
data Object
additional meta data specific to the picker type when applicable

Returns

the value from the picker or null if the operation was canceled.

log

public static void log(String s)
Prints to the log

Parameters

s String
the string

log

public static void log(Throwable s)
Prints to the log

Parameters

s Throwable
the exception

sendLog

public static void sendLog()
Sends the log to your email account

sendMessage

public static void sendMessage(String subject, Message msg, String... recipients)

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

subject String
e-mail subject
msg Message
the Message to send
recipients String...
array of e-mail addresses

isSimulator

public static boolean isSimulator()
Allows detecting development mode so debugging code and special cases can be used to simplify flow

Returns

true if we are running in the simulator, false otherwise

addDefaultHeader

public static void addDefaultHeader(String key, String value)
Adds a header to the global default headers, this header will be implicitly added to all requests going out from this point onwards. The main use case for this is for authentication information communication via the header.

Parameters

key String
the key of the header
value String
the value of the header

addToQueueAndWait

public static void addToQueueAndWait(ConnectionRequest request)
Identical to add to queue but waits until the request is processed in the queue, this is useful for completely synchronous operations.

Parameters

request ConnectionRequest
the request object to add

addToQueue

public static void addToQueue(ConnectionRequest request)
Adds the given network connection to the queue of execution

Parameters

request ConnectionRequest
network request for execution

killAndWait

public static void killAndWait(ConnectionRequest request)
Kills the given request and waits until the request is killed if it is being processed by one of the threads. This method must not be invoked from a network thread!

addNetworkErrorListener

public static void addNetworkErrorListener(ActionListener<NetworkEvent> e)
Adds a generic listener to a network error that is invoked before the exception is propagated. Note that this handles also server error codes by default! You can change this default behavior setting to false ConnectionRequest.setHandleErrorCodesInGlobalErrorHandler(boolean). Consume the event in order to prevent it from propagating further.

Parameters

e ActionListener<NetworkEvent>
callback will be invoked with the Exception as the source object

removeNetworkErrorListener

public static void removeNetworkErrorListener(ActionListener<NetworkEvent> e)
Removes the given error listener

Parameters

e ActionListener<NetworkEvent>
callback to remove

addNetworkProgressListener

public static void addNetworkProgressListener(ActionListener<NetworkEvent> al)
Adds a listener to be notified when progress updates

Parameters

al ActionListener<NetworkEvent>
action listener

removeNetworkProgressListener

public static void removeNetworkProgressListener(ActionListener<NetworkEvent> al)
Adds a listener to be notified when progress updates

Parameters

al ActionListener<NetworkEvent>
action listener

updateNetworkThreadCount

public static void updateNetworkThreadCount(int threadCount)
Sets the number of network threads and restarts the network threads

Parameters

threadCount int
the new number of threads

clearStorageCache

public static void clearStorageCache()
Storage is cached for faster access, however this might cause a problem with refreshing objects since they are not cloned. Clearing the cache allows to actually reload from the storage file.

flushStorageCache

public static void flushStorageCache()
Flush the storage cache allowing implementations that cache storage objects to store

deleteStorageFile

public static void deleteStorageFile(String name)
Deletes the given file name from the storage

Parameters

name String
the name of the storage file

clearStorage

public static void clearStorage()
Deletes all the files in the application storage

createStorageOutputStream

public static OutputStream createStorageOutputStream(String name) throws IOException
Creates an output stream to the storage with the given name

Parameters

name String
the storage file name

Returns

an output stream of limited capacity

createStorageInputStream

public static InputStream createStorageInputStream(String name) throws IOException
Creates an input stream to the given storage source file

Parameters

name String
the name of the source file

Returns

the input stream

existsInStorage

public static boolean existsInStorage(String name)
Returns true if the given storage file exists

Parameters

name String
the storage file name

Returns

true if it exists

listStorageEntries

public static String[] listStorageEntries()
Lists the names of the storage files

Returns

the names of all the storage files

storageEntrySize

public static int storageEntrySize(String name)
Returns the size in bytes of the given entry

Parameters

name String
the name of the entry

Returns

the size in bytes

writeObjectToStorage

public static boolean writeObjectToStorage(String name, Object o)

Writes the given object to storage assuming it is an externalizable type or one of the supported types.

The sample below demonstrates the usage and registration of the com.codename1.io.Externalizable interface:

// File: Main.java
public class Main {
  public void init(Object o) {
    theme = UIManager.initFirstTheme("/theme");

    // IMPORTANT: Notice we don't use MyClass.class.getName()! This won't work due to obfuscation!
    Util.register("MyClass", MyClass.class);
  }

  public void start() {
    //...
  }

  public void stop() {
    //...
  }

  public void destroy() {
    //...
  }
}
// File: MyClass.java
public class MyClass implements Externalizable {
  // allows us to manipulate the version, in this case we are demonstrating a data change between the initial release
  // and the current state of object data
  private static final int VERSION = 2;

  private String name;
  private Map data;

  // this field was added after version 1
  private Date startedAt;

  public int getVersion() {
    return VERSION;
  }

  public void externalize(DataOutputStream out) throws IOException {
    Util.writeUTF(name, out);
    Util.writeObject(data, out);
    if(startedAt != null) {
        out.writeBoolean(true);
        out.writeLong(startedAt.getTime());
    } else {
        out.writeBoolean(false);
    }
  }
  public void internalize(int version, DataInputStream in) throws IOException {
    name = Util.readUTF(in);
    data = (Map)Util.readObject(in);
    if(version > 1) {
        boolean hasDate = in.readBoolean();
        if(hasDate) {
            startedAt = new Date(in.readLong());
        }
    }
  }
  public String getObjectId() {
    // IMPORTANT: Notice we don't use getClass().getName()! This won't work due to obfuscation!
    return "MyClass";
  }
}
// File: ReadAndWrite.java
// will read the file or return null if failed
MyClass object = (MyClass)Storage.getInstance().readObject("NameOfFile");

// write the object back to storage
Storage.getInstance().writeObject("NameOfFile", object);

Parameters

name String
store name
o Object
object to store

Returns

true for success, false for failure

readObjectFromStorage

public static Object readObjectFromStorage(String name)

Reads the object from the storage, returns null if the object isn’t there

The sample below demonstrates the usage and registration of the com.codename1.io.Externalizable interface:

// File: Main.java
public class Main {
  public void init(Object o) {
    theme = UIManager.initFirstTheme("/theme");

    // IMPORTANT: Notice we don't use MyClass.class.getName()! This won't work due to obfuscation!
    Util.register("MyClass", MyClass.class);
  }

  public void start() {
    //...
  }

  public void stop() {
    //...
  }

  public void destroy() {
    //...
  }
}
// File: MyClass.java
public class MyClass implements Externalizable {
  // allows us to manipulate the version, in this case we are demonstrating a data change between the initial release
  // and the current state of object data
  private static final int VERSION = 2;

  private String name;
  private Map data;

  // this field was added after version 1
  private Date startedAt;

  public int getVersion() {
    return VERSION;
  }

  public void externalize(DataOutputStream out) throws IOException {
    Util.writeUTF(name, out);
    Util.writeObject(data, out);
    if(startedAt != null) {
        out.writeBoolean(true);
        out.writeLong(startedAt.getTime());
    } else {
        out.writeBoolean(false);
    }
  }
  public void internalize(int version, DataInputStream in) throws IOException {
    name = Util.readUTF(in);
    data = (Map)Util.readObject(in);
    if(version > 1) {
        boolean hasDate = in.readBoolean();
        if(hasDate) {
            startedAt = new Date(in.readLong());
        }
    }
  }
  public String getObjectId() {
    // IMPORTANT: Notice we don't use getClass().getName()! This won't work due to obfuscation!
    return "MyClass";
  }
}
// File: ReadAndWrite.java
// will read the file or return null if failed
MyClass object = (MyClass)Storage.getInstance().readObject("NameOfFile");

// write the object back to storage
Storage.getInstance().writeObject("NameOfFile", object);

Parameters

name String
name of the store

Returns

object stored under that name

getFileSystemRoots

public static String[] getFileSystemRoots()
Returns the filesystem roots from which the structure of the file system can be traversed

Returns

the roots of the filesystem

getFileSystemRootType

public static int getFileSystemRootType(String root)
Returns the type of the root often by guessing

Parameters

root String
the root whose type we are checking

Returns

one of the type constants above

listFiles

public static String[] listFiles(String directory) throws IOException
Lists the files within the given directory, returns relative file names and not full file names.

Parameters

directory String
the directory in which files should be listed

Returns

array of file names

getFileSystemRootSizeBytes

public static long getFileSystemRootSizeBytes(String root)
Returns the size of the given root directory

Parameters

root String
the root directory in the filesystem

Returns

the byte size of the directory

getFileSystemRootAvailableSpace

public static long getFileSystemRootAvailableSpace(String root)
Returns the available space in the given root directory

Parameters

root String
the root directory in the filesystem

Returns

the bytes available in the directory

mkdir

public static void mkdir(String directory)
Creates the given directory

Parameters

directory String
the directory name to create

delete

public static void delete(String file)
Deletes the specific file or empty directory.

Parameters

file String
file or empty directory to delete

existsInFileSystem

public static boolean existsInFileSystem(String file)
Indicates whether a file exists

Parameters

file String
the file to check

Returns

true if the file exists and false otherwise

isHiddenFile

public static boolean isHiddenFile(String file)
Indicates the hidden state of the file

Parameters

file String
file

Returns

true for a hidden file

setHiddenFile

public static void setHiddenFile(String file, boolean h)
Toggles the hidden state of the file

Parameters

file String
file
h boolean
hidden state

renameFile

public static void renameFile(String file, String newName)
Renames a file to the given name, expects the new name to be relative to the current directory

Parameters

file String
absolute file name
newName String
relative new name

getFileLength

public static long getFileLength(String file)
Returns the length of the file

Parameters

file String
file

Returns

length of said file

getFileLastModifiedFile

public static long getFileLastModifiedFile(String file)
Deprecated. this API requires additional privacy permissions on iOS and might cause problems with iOS submissions
Returns the time that the file denoted by this abstract pathname was last modified.

Returns

A long value representing the time the file was last modified, measured in milliseconds

isDirectory

public static boolean isDirectory(String file)
Indicates whether the given file is a directory

Parameters

file String
file

Returns

true if its a directory

openFileOutputStream

public static OutputStream openFileOutputStream(String file) throws IOException
Opens an output stream to the given file

Parameters

file String
the file

Returns

the output stream

openFileInputStream

public static InputStream openFileInputStream(String file) throws IOException
Opens an input stream to the given file

Parameters

file String
the file

Returns

the input stream

openFileOutputStream

public static OutputStream openFileOutputStream(String file, int offset) throws IOException
Opens an output stream to the given file

Parameters

file String
the file
offset int
position in the file

Returns

the output stream

getAppHomePath

public static String getAppHomePath()

The application home directory is a “safe place” to store files for this application in a portable way. On some platforms such as Android & iOS this path may be visible only to the application itself, other apps won’t have permission to access this path.

The sample below uses the app home directory to save a file so we can share it using the com.codename1.components.ShareButton:

Form hi = new Form("ShareButton");
ShareButton sb = new ShareButton();
sb.setText("Share Screenshot");
hi.add(sb);

Image screenshot = Image.createImage(hi.getWidth(), hi.getHeight());
hi.revalidate();
hi.setVisible(true);
hi.paintComponent(screenshot.getGraphics(), true);

String imageFile = FileSystemStorage.getInstance().getAppHomePath() + "screenshot.png";
try(OutputStream os = FileSystemStorage.getInstance().openOutputStream(imageFile)) {
    ImageIO.getImageIO().save(screenshot, os, ImageIO.FORMAT_PNG, 1);
} catch(IOException err) {
    Log.e(err);
}
sb.setImageToShare(imageFile, "image/png");

Returns

a writable directory that represent the application home directory

hasCachesDir

public static boolean hasCachesDir()
Returns true if the device has a directory dedicated for “cache” files

Returns

true if a caches style directory exists in this device type

getCachesDir

public static String getCachesDir()
Returns a device specific directory designed for cache style files, or null if #hasCachesDir() is false

Returns

file URL or null

canInstallOnHomescreen

public static 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

True if you are able to prompt the user to install the app on their homescreen.

promptInstallOnHomescreen

public static boolean promptInstallOnHomescreen()
Prompts the user to install this app on their homescreen. This is only relevant in the javascript port.

Returns

The result of the user prompt. true if the user accepts the installation, false if they reject it.

onCanInstallOnHomescreen

public static void onCanInstallOnHomescreen(Runnable r)
A callback fired when you are allowed to prompt the user to install the app on their homescreen. Only relevant in the javascript port.

Parameters

r Runnable
Runnable that will be run when/if you are permitted to prompt the user to install the app on their homescreen.

captureScreen

public static Image captureScreen()
Captures a screenshot of the screen.

Returns

An image of the screen, or null if it fails.

addMessageListener

public static void addMessageListener(ActionListener<MessageEvent> l)

Adds a listener to receive messages from the native platform. This is a mechanism to communicate between the app and the native platform. Currently the Javascript port is the only port to use this mechanism.

In the Javascript port, javascript can send messages to the CN1 app by calling

window.dispatchEvent(new CustomEvent('cn1inbox', {detail:'The message', code: SOMEINTEGER)); }

Parameters

l ActionListener<MessageEvent>
The listener.

removeMessageListener

public static void removeMessageListener(ActionListener<MessageEvent> l)
Removes a listener from receiving messages from the native platform. This is a mechanism to communicate between the app and the native platform. Currently the Javascript port is the only port to use this mechanism.

Parameters

l ActionListener<MessageEvent>
The listener.

postMessage

public static void postMessage(MessageEvent message)

Posts a message to the native platform. This is a mechanism to communicate between the app and the native platform. Currently the Javascript port is the only port to use this mechanism.

In the Javascript port these messages can be received in Javascript by adding an event listener for ‘cn1outbox’ events to the ‘window’ object. The message is contained in the event data “detail” key. And the code in the ‘code’ key.

Parameters

message MessageEvent
The message to send to the native platform.

setTimeout

public static Timer setTimeout(int timeout, Runnable r)
Convenience method to schedule a task to run on the EDT after timeoutms.

Parameters

timeout int
The timeout in milliseconds.
r Runnable
The task to run.

Returns

The Timer object that can be used to cancel the task.

setInterval

public static Timer setInterval(int timeout, Runnable r)
Convenience method to schedule a task to run on the EDT after periodms repeating every periodms.

Parameters

timeout int
The delay and repeat in milliseconds.
r Runnable
The runnable to run on the EDT.

Returns

The timer object which can be used to cancel the task.

getSharedJavascriptContext

public static BrowserComponent getSharedJavascriptContext()

Gets a reference to an application-wide shared Javascript context that can be used for running Javascript commands. When running in the Javascript port, this Javascript context will be the same context in which the application itself is running, so it gives you the ability to interact with the browser and DOM directly using the familiar BrowserComponent API.

When running on other platforms, this shared context will be an off-screen browser component.

Sample code allowing user to execute arbitrary Javascript code inside the shared context:

Form hi = new Form("Hi World", new BorderLayout());
TextArea input = new TextArea();
TextArea output = new TextArea();
output.setEditable(false);

Button execute = new Button("Run");
execute.addActionListener(evt->{
    BrowserComponent bc = CN.getSharedJavascriptContext().ready().get();
    bc.execute("callback.onSuccess(window.eval(${0}))", new Object[]{input.getText()}, res->{
        output.setText(res.toString());
    });
});
SplitPane split = new SplitPane(SplitPane.VERTICAL_SPLIT, input, output, "0", "50%", "99%");
hi.add(CENTER, split);
hi.add(NORTH, execute);

hi.show();

Returns

A shared BrowserComponent

getPluginSupport

public static PluginSupport getPluginSupport()
Returns the plugin support object for the current platform. Use this object for registering plugins.

Returns

The plugin support object.