public class CN
Known subtypesFont
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 = 32 | Constant allowing us to author portable system fonts |
public static final int FACE_PROPORTIONAL = 64 | Constant allowing us to author portable system fonts |
public static final int FACE_SYSTEM = 0 | Constant allowing us to author portable system fonts |
public static final int SIZE_LARGE = 16 | Constant allowing us to author portable system fonts |
public static final int SIZE_MEDIUM = 0 | Constant allowing us to author portable system fonts |
public static final int SIZE_SMALL = 8 | Constant allowing us to author portable system fonts |
public static final int STYLE_BOLD = 1 | Constant allowing us to author portable system fonts |
public static final int STYLE_ITALIC = 2 | Constant allowing us to author portable system fonts |
public static final int STYLE_UNDERLINED = 4 | Constant allowing us to author portable system fonts |
public static final int STYLE_PLAIN = 0 | Constant 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 = 4 | Indicates a Component center alignment |
public static final int TOP = 0 | Box-orientation constant used to specify the top of a box. |
public static final int LEFT = 1 | Box-orientation constant used to specify the left side of a box. |
public static final int BOTTOM = 2 | Box-orientation constant used to specify the bottom of a box. |
public static final int RIGHT = 3 | Box-orientation constant used to specify the right side of a box. |
public static final int BASELINE = 5 | Alignment to the baseline constraint |
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 |
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. |
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 |
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 |
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 IOException | Sends a SMS message to the given phone number |
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. |
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 IOException | Creates an output stream to the storage with the given name |
public static InputStream createStorageInputStream(String name)
throws IOException | Creates 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 IOException | Lists 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 IOException | Opens an output stream to the given file |
public static InputStream openFileInputStream(String file)
throws IOException | Opens an input stream to the given file |
public static OutputStream openFileOutputStream(String file, int offset)
throws IOException | Opens 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
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
NATIVE_MAIN_THIN
public static final String NATIVE_MAIN_THIN = "native:MainThin"NATIVE_MAIN_LIGHT
public static final String NATIVE_MAIN_LIGHT = "native:MainLight"NATIVE_MAIN_REGULAR
public static final String NATIVE_MAIN_REGULAR = "native:MainRegular"NATIVE_MAIN_BOLD
public static final String NATIVE_MAIN_BOLD = "native:MainBold"NATIVE_MAIN_BLACK
public static final String NATIVE_MAIN_BLACK = "native:MainBlack"NATIVE_ITALIC_THIN
public static final String NATIVE_ITALIC_THIN = "native:ItalicThin"NATIVE_ITALIC_LIGHT
public static final String NATIVE_ITALIC_LIGHT = "native:ItalicLight"NATIVE_ITALIC_REGULAR
public static final String NATIVE_ITALIC_REGULAR = "native:ItalicRegular"NATIVE_ITALIC_BOLD
public static final String NATIVE_ITALIC_BOLD = "native:ItalicBold"NATIVE_ITALIC_BLACK
public static final String NATIVE_ITALIC_BLACK = "native:ItalicBlack"FACE_MONOSPACE
public static final int FACE_MONOSPACE = 32FACE_PROPORTIONAL
public static final int FACE_PROPORTIONAL = 64FACE_SYSTEM
public static final int FACE_SYSTEM = 0SIZE_LARGE
public static final int SIZE_LARGE = 16SIZE_MEDIUM
public static final int SIZE_MEDIUM = 0SIZE_SMALL
public static final int SIZE_SMALL = 8STYLE_BOLD
public static final int STYLE_BOLD = 1STYLE_ITALIC
public static final int STYLE_ITALIC = 2STYLE_UNDERLINED
public static final int STYLE_UNDERLINED = 4STYLE_PLAIN
public static final int STYLE_PLAIN = 0NORTH
public static final String NORTH = "North"SOUTH
public static final String SOUTH = "South"WEST
public static final String WEST = "West"EAST
public static final String EAST = "East"CENTER
public static final int CENTER = 4TOP
public static final int TOP = 0LEFT
public static final int LEFT = 1BOTTOM
public static final int BOTTOM = 2RIGHT
public static final int RIGHT = 3BASELINE
public static final int BASELINE = 5CENTER_BEHAVIOR_SCALE
public static final int CENTER_BEHAVIOR_SCALE = 0CENTER_BEHAVIOR_CENTER
public static final int CENTER_BEHAVIOR_CENTER = 1CENTER_BEHAVIOR_CENTER_ABSOLUTE
public static final int CENTER_BEHAVIOR_CENTER_ABSOLUTE = 2CENTER_BEHAVIOR_TOTAL_BELOW
public static final int CENTER_BEHAVIOR_TOTAL_BELOW = 3Method 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
bookmarkRunnable- A
Runnablethat can be run to restore the app to a particular point.
restoreToBookmark
public static void restoreToBookmark()#setBookmark(java.lang.Runnable)getDragStartPercentage
public static int getDragStartPercentage()Returns
setDragStartPercentage
public static void setDragStartPercentage(int dragStartPercentage)Parameters
dragStartPercentageint- percentage of the screen required to initiate drag
createSoftWeakRef
public static Object createSoftWeakRef(Object o)Parameters
oObject- object to cache
Returns
extractHardRef
public static Object extractHardRef(Object o)Parameters
oObject- the reference returned by createSoftWeakRef
Returns
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
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
enableboolean- True to enable async stack traces.
See also
vibrate
public static void vibrate(int duration)Parameters
durationint- length of time to vibrate (might be ignored)
announceForAccessibility
public static 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 static void announceForAccessibility(String text)Parameters
textString- the message to announce
isEdt
public static boolean isEdt()Returns
callSerially
public static 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 static 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
scheduleBackgroundTask
public static void scheduleBackgroundTask(Runnable r)Parameters
rRunnable- the task to perform in the background
callSeriallyAndWait
public static 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).
callSeriallyAndWait
public static 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).
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
rRunnable- runnable (NOT A THREAD!) that will be invoked synchroniously by this method
invokeWithoutBlocking
public static 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 static <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>- Runnable to be run immediately.
Throws
BlockingDisallowedException- If
#invokeAndBlock(java.lang.Runnable)is attempted anywhere in the Runnable.
minimizeApplication
public static boolean minimizeApplication()Returns
isMinimized
public static boolean isMinimized()Returns
restoreMinimizedApplication
public static void restoreMinimizedApplication()getCurrentForm
public static Form getCurrentForm()Returns
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
getDisplayWidth
public static int getDisplayWidth()Returns
getDisplayHeight
public static int getDisplayHeight()Returns
convertToPixels
public static 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 static 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 static 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 static int convertToPixels(float dipCount)Parameters
dipCountfloat- the dips that we will convert to pixels
Returns
getResourceAsStream
public static InputStream getResourceAsStream(String resource)Parameters
resourceString- relative/absolute URL based on the Java convention
Returns
addEdtErrorHandler
public static void addEdtErrorHandler(ActionListener e)Parameters
eActionListener- listener receiving the errors
removeEdtErrorHandler
public static void removeEdtErrorHandler(ActionListener e)Parameters
eActionListener- listener receiving the errors
exitApplication
public static void exitApplication()exitAndClearTask
public static 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 static boolean isExitAndClearTaskSupported()#exitAndClearTask() is still legal, it just behaves
exactly like #exitApplication().Returns
See also
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
keyString- the key of the property
defaultValueString- a default return value
Returns
setProperty
public static void setProperty(String key, String value)Parameters
keyString- key the key of the property
valueString- 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
urlString- the url that would be executed
Returns
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
urlString- the url to execute
downloadBytesAsFile
public static 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 static int getDeviceDensity()Returns
isPortrait
public static boolean isPortrait()Returns
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
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
isInFullScreenMode
public static boolean isInFullScreenMode()Returns
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
canForceOrientation
public static boolean canForceOrientation()Returns
lockOrientation
public static void lockOrientation(boolean portrait)Parameters
portraitboolean- true to lock to portrait mode, false to lock to landscape mode
isLockOrientation
public static boolean isLockOrientation()Returns
unlockOrientation
public static void unlockOrientation()isTablet
public static boolean isTablet()Returns
isDesktop
public static boolean isDesktop()Returns
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
com.codename1.ui.WindowisWatch
public static boolean isWatch()Returns
isTV
public static boolean isTV()Returns
isCarConnected
public static boolean isCarConnected()com.codename1.car experience.Returns
getCurrentPointerEvent
public static PointerEvent getCurrentPointerEvent()Returns
com.codename1.ui.events.PointerEvent, never nullgetPointerButton
public static int getPointerButton()com.codename1.ui.events.PointerEvent BUTTON_* constants.getPressedButtonMask
public static int getPressedButtonMask()com.codename1.ui.events.PointerEvent MASK_* constants.getPointerType
public static int getPointerType()com.codename1.ui.events.PointerEvent TYPE_*
constants (finger, mouse, stylus or eraser).getPointerPressure
public static float getPointerPressure()0.0 and 1.0. Devices and
ports that do not report pressure return 1.0.getPointerTiltX
public static float getPointerTiltX()0 when not reported.getPointerTiltY
public static float getPointerTiltY()0 when not reported.getPointerContactSize
public static float getPointerContactSize()0.0 and 1.0, or 0 when not reported.isStylusPointer
public static boolean isStylusPointer()isFoldable
public static boolean isFoldable()getDevicePosture
public static DevicePosture getDevicePosture()com.codename1.ui.DevicePosture.addPostureListener
public static void addPostureListener(ActionListener l)Parameters
lActionListener- the listener to add
removePostureListener
public static void removePostureListener(ActionListener l)Parameters
lActionListener- the listener to remove
isDesktopMode
public static boolean isDesktopMode()getDisplayCount
public static int getDisplayCount()isExternalDisplayConnected
public static boolean isExternalDisplayConnected()getDesktopSize
public static Dimension getDesktopSize()Returns
getWindowBounds
public static Rectangle getWindowBounds()Returns
setWindowSize
public static void setWindowSize(int width, int height)Parameters
widthint- the desired window width
heightint- the desired window height
getInitialWindowSizeHintPercent
public static Dimension getInitialWindowSizeHintPercent()Returns
nullsetInitialWindowSizeHintPercent
public static 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
addWindowListener
public static void addWindowListener(ActionListener<WindowEvent> l)Parameters
lActionListener<WindowEvent>- the listener to add
removeWindowListener
public static void removeWindowListener(ActionListener<WindowEvent> l)Parameters
lActionListener<WindowEvent>- the listener to remove
canDial
public static boolean canDial()Returns
isDarkMode
public static Boolean isDarkMode()Returns
isHighContrastEnabled
public static boolean isHighContrastEnabled()isDifferentiateWithoutColorEnabled
public static boolean isDifferentiateWithoutColorEnabled()getColorVisionDeficiency
public static AccessibilityColorVisionDeficiency getColorVisionDeficiency()isReduceMotionEnabled
public static boolean isReduceMotionEnabled()isReduceTransparencyEnabled
public static boolean isReduceTransparencyEnabled()isBoldTextEnabled
public static boolean isBoldTextEnabled()isInvertColorsEnabled
public static boolean isInvertColorsEnabled()isGrayscaleEnabled
public static boolean isGrayscaleEnabled()isOnOffSwitchLabelsEnabled
public static boolean isOnOffSwitchLabelsEnabled()isScreenReaderEnabled
public static boolean isScreenReaderEnabled()setDarkMode
public static void setDarkMode(Boolean darkMode)Parameters
darkModeBoolean- 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
responseActionListener- a callback Object to retrieve the file path
typeint- 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
responseActionListener- callback receiving the selected file path
acceptString- comma-separated extensions or MIME types, or
nullfor all files
getPlatformName
public static String getPlatformName()Returns
getSimd
public static Simd getSimd()isGpuSupported
public static boolean isGpuSupported()com.codename1.gpu.RenderView.dial
public static void dial(String phoneNumber)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
sendSMS
public static void sendSMS(String phoneNumber, String message)
throws IOExceptionParameters
phoneNumberString- to send the sms
messageString- the content of the sms
Throws
sendSMS
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.
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
isNativeInAppReviewSupported
public static boolean isNativeInAppReviewSupported()AppReview API falls back to a Codename One
drawn rating widget.Returns
requestNativeInAppReview
public static 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.
registerPush
public static void registerPush()deregisterPush
public static void deregisterPush()createThread
public static 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 static 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
isScreenSaverDisableSupported
public static boolean isScreenSaverDisableSupported()setScreenSaverEnabled
public static 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 static boolean hasCamera()isNativePickerTypeSupported
public static boolean isNativePickerTypeSupported(int pickerType)Parameters
pickerTypeint- the picker type constant
Returns
showNativePicker
public static 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
log
public static void log(String s)Parameters
sString- the string
log
public static void log(Throwable s)Parameters
sThrowable- the exception
sendLog
public static void sendLog()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
subjectString- e-mail subject
msgMessage- the Message to send
recipientsString...- array of e-mail addresses
isSimulator
public static boolean isSimulator()Returns
addDefaultHeader
public static void addDefaultHeader(String key, String value)Parameters
keyString- the key of the header
valueString- the value of the header
addToQueueAndWait
public static void addToQueueAndWait(ConnectionRequest request)Parameters
requestConnectionRequest- the request object to add
addToQueue
public static void addToQueue(ConnectionRequest request)Parameters
requestConnectionRequest- network request for execution
killAndWait
public static void killAndWait(ConnectionRequest request)addNetworkErrorListener
public static void addNetworkErrorListener(ActionListener<NetworkEvent> e)Parameters
eActionListener<NetworkEvent>- callback will be invoked with the Exception as the source object
removeNetworkErrorListener
public static void removeNetworkErrorListener(ActionListener<NetworkEvent> e)Parameters
eActionListener<NetworkEvent>- callback to remove
addNetworkProgressListener
public static void addNetworkProgressListener(ActionListener<NetworkEvent> al)Parameters
alActionListener<NetworkEvent>- action listener
removeNetworkProgressListener
public static void removeNetworkProgressListener(ActionListener<NetworkEvent> al)Parameters
alActionListener<NetworkEvent>- action listener
updateNetworkThreadCount
public static void updateNetworkThreadCount(int threadCount)Parameters
threadCountint- the new number of threads
clearStorageCache
public static void clearStorageCache()flushStorageCache
public static void flushStorageCache()deleteStorageFile
public static void deleteStorageFile(String name)Parameters
nameString- the name of the storage file
clearStorage
public static void clearStorage()createStorageOutputStream
public static OutputStream createStorageOutputStream(String name)
throws IOExceptionParameters
nameString- the storage file name
Returns
Throws
createStorageInputStream
public static InputStream createStorageInputStream(String name)
throws IOExceptionParameters
nameString- the name of the source file
Returns
Throws
existsInStorage
public static boolean existsInStorage(String name)Parameters
nameString- the storage file name
Returns
listStorageEntries
public static String[] listStorageEntries()Returns
storageEntrySize
public static int storageEntrySize(String name)Parameters
nameString- the name of the entry
Returns
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
nameString- store name
oObject- object to store
Returns
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
nameString- name of the store
Returns
getFileSystemRoots
public static String[] getFileSystemRoots()Returns
getFileSystemRootType
public static int getFileSystemRootType(String root)Parameters
rootString- the root whose type we are checking
Returns
listFiles
public static String[] listFiles(String directory)
throws IOExceptionParameters
directoryString- the directory in which files should be listed
Returns
Throws
getFileSystemRootSizeBytes
public static long getFileSystemRootSizeBytes(String root)Parameters
rootString- the root directory in the filesystem
Returns
getFileSystemRootAvailableSpace
public static long getFileSystemRootAvailableSpace(String root)Parameters
rootString- the root directory in the filesystem
Returns
mkdir
public static void mkdir(String directory)Parameters
directoryString- the directory name to create
delete
public static void delete(String file)Parameters
fileString- file or empty directory to delete
existsInFileSystem
public static boolean existsInFileSystem(String file)Parameters
fileString- the file to check
Returns
isHiddenFile
public static boolean isHiddenFile(String file)Parameters
fileString- file
Returns
setHiddenFile
public static void setHiddenFile(String file, boolean h)Parameters
fileString- file
hboolean- hidden state
renameFile
public static void renameFile(String file, String newName)Parameters
fileString- absolute file name
newNameString- relative new name
getFileLength
public static long getFileLength(String file)Parameters
fileString- file
Returns
getFileLastModifiedFile
public static long getFileLastModifiedFile(String file)Returns
isDirectory
public static boolean isDirectory(String file)Parameters
fileString- file
Returns
openFileOutputStream
public static OutputStream openFileOutputStream(String file)
throws IOExceptionParameters
fileString- the file
Returns
Throws
openFileInputStream
public static InputStream openFileInputStream(String file)
throws IOExceptionParameters
fileString- the file
Returns
Throws
openFileOutputStream
public static OutputStream openFileOutputStream(String file, int offset)
throws IOExceptionParameters
fileString- the file
offsetint- position in the file
Returns
Throws
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
hasCachesDir
public static boolean hasCachesDir()Returns
getCachesDir
public static String getCachesDir()#hasCachesDir()
is falseReturns
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
promptInstallOnHomescreen
public static boolean promptInstallOnHomescreen()Returns
onCanInstallOnHomescreen
public static 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 static Image captureScreen()Returns
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
lActionListener<MessageEvent>- The listener.
removeMessageListener
public static void removeMessageListener(ActionListener<MessageEvent> l)Parameters
lActionListener<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
messageMessageEvent- The message to send to the native platform.
setTimeout
public static Timer setTimeout(int timeout, Runnable r)Parameters
timeoutint- The timeout in milliseconds.
rRunnable- The task to run.
Returns
setInterval
public static Timer setInterval(int timeout, Runnable r)Parameters
timeoutint- The delay and repeat in milliseconds.
rRunnable- The runnable to run on the EDT.
Returns
getPluginSupport
public static PluginSupport getPluginSupport()