Class Vm


  • public final class Vm
    extends java.lang.Object
    Vm contains various system-level methods.

    This class contains methods to copy arrays, obtain a timestamp, sleep and get platform and version information, among many other things.

    • Field Summary

      Fields 
      Modifier and Type Field Description
      static java.lang.String ALTERNATIVE_DEBUG
      Deprecated.
      In Android, it writes things on DebugConsole.txt and on ADB, so this is now useless
      static boolean disableDebug
      Set to true to disable Vm.debug message output.
      static java.lang.String ERASE_DEBUG
      Pass this to Vm.debug to erase the memo/txt file used to store the output.
      static int[] keysBeingIntercepted
      Internal use only.
      static int TWEAK_AUDIBLE_GC
      Each time the garbage collector runs, it will issue a beep.
      static int TWEAK_DISABLE_GC
      Disables the Garbage Collector.
      static int TWEAK_DUMP_MEM_STATS
      When the program ends, it will dump the memory status of the program with the following information: Times gc was called: number of times the garbage collector was called.
      static int TWEAK_MEM_PROFILER
      Computes the maximum memory in use between two consecutive calls.
      static int TWEAK_TRACE_CREATED_CLASSOBJS
      This flag turns on the trace of created class objects.
      static int TWEAK_TRACE_LOCKED_OBJS
      This flag turns on the trace of locked objects, which are objects that are locked by the vm and will never be released.
      static int TWEAK_TRACE_METHODS
      Enables dump of executed methods to the console.
      static int TWEAK_TRACE_OBJECTS_LEFT_BETWEEN_2_GCS
      This flag turns on the trace objects that are left behind between two garbage collector calls.
    • Method Summary

      All Methods Static Methods Concrete Methods Deprecated Methods 
      Modifier and Type Method Description
      static void alert​(java.lang.String s)
      Shows an alert IMMEDIATELY on screen.
      static boolean arrayCopy​(java.lang.Object srcArray, int srcStart, java.lang.Object dstArray, int dstStart, int length)
      Copies the elements of one array to another array.
      static boolean attachLibrary​(java.lang.String name)
      Deprecated.
      This method never worked in TotalCross.
      static boolean attachNativeLibrary​(java.lang.String name)
      Attaches a native library to this application instance (only works at device).
      static void clipboardCopy​(java.lang.String s)
      Copies the specific string to the clipboard.
      static java.lang.String clipboardPaste()
      Gets the last string from the clipboard.
      static void debug​(java.lang.String s)
      Sends a text, preceeded with the current time stamp and followed by a line feed, to: Windows CE / 32: the "DebugConsole.txt" file at the current application's folder Blackberry: the event logger, which can be accessed using alt+LGLG iPhone: the "DebugConsole.txt" file in the application's folder.
      static int exec​(java.lang.String command, java.lang.String args, int launchCode, boolean wait)
      Executes a command.
      static void exitAndReboot()
      Reboots the device.
      static void gc()
      Calls the Garbage Collector.
      static byte[] getFile​(java.lang.String name)
      Returns a byte array of a file contained in the same tcz where this one resides, or in some attached library (or JAR, if application is running in a browser).
      static int getFreeMemory()
      Returns the free memory in the device.
      static int getRemainingBattery()
      Returns the percentage of the remaining battery life of this device.
      static java.lang.String getStackTrace()
      A shortcut for try {throw new Exception();} catch (Exception e) {return getStackTrace(e);}
      static java.lang.String getStackTrace​(java.lang.Throwable t)
      Returns the given throwable stack trace as a String.
      static int getTimeStamp()
      Returns a time stamp in milliseconds.
      static int identityHashCode​(java.lang.Object object)
      Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode().
      static void interceptSpecialKeys​(int[] keys)
      Specify which special keys to intercept; use the constants available in SpecialKeys or pass device-specific constants, which can be retrieved calling Vm.showKeyCodes(true).
      static boolean isKeyDown​(int key)
      Gets the current keys being pressed.
      static void preallocateArray​(java.lang.Object sample, int length)
      This method pre-allocates space for an array of objects with the given length.
      static void printStackTrace()
      Prints the stack trace to the debug console file.
      static void printStackTrace​(java.lang.String msg)
      Prints the stack trace to the debug console file with the given message.
      static void safeSleep​(int millis)
      Causes the VM (or the current thread, if called from it) to pause execution for aproximately the given number of milliseconds.
      static void setAutoOff​(boolean enabled)
      Enables or disables device automatic turn-off, which happens after a period of inactivity of the device.
      static void setTime​(Time t)
      Deprecated.
      It won't work on most devices.
      static void showKeyCodes​(boolean on)
      Set to true to popup an alert for each key pressed.
      static void sleep​(int millis)
      Causes the VM (or the current thread, if called from it) to pause execution for the given number of milliseconds.
      static boolean turnScreenOn​(boolean on)
      Turns the screen on or off, but keeps the device running.
      static void tweak​(int param, boolean set)
      Tweak some parameters of the virtual machine.
      static void vibrate​(int millis)
      Vibrates the device for the specified number of milliseconds.
      static void warning​(java.lang.String s)
      This function can be used to show permanent warnings.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • keysBeingIntercepted

        public static int[] keysBeingIntercepted
        Internal use only. Used only at desktop.
      • ERASE_DEBUG

        public static final java.lang.String ERASE_DEBUG
        Pass this to Vm.debug to erase the memo/txt file used to store the output.
        See Also:
        Constant Field Values
      • ALTERNATIVE_DEBUG

        @Deprecated
        public static final java.lang.String ALTERNATIVE_DEBUG
        Deprecated.
        In Android, it writes things on DebugConsole.txt and on ADB, so this is now useless
        See Also:
        Constant Field Values
      • disableDebug

        public static boolean disableDebug
        Set to true to disable Vm.debug message output. Note that the method calls will still remain, and can slowdown your program. Note also that Vm.warning is not affected by this flag.
        Since:
        SuperWaba 5.52
      • TWEAK_AUDIBLE_GC

        public static final int TWEAK_AUDIBLE_GC
        Each time the garbage collector runs, it will issue a beep. To be used in the tweak method.
        See Also:
        Constant Field Values
      • TWEAK_DUMP_MEM_STATS

        public static final int TWEAK_DUMP_MEM_STATS
        When the program ends, it will dump the memory status of the program with the following information:
        • Times gc was called: number of times the garbage collector was called.
        • Total gc time: total time in milisseconds that the gc took
        • Chunks created: number of chunks (block of memory used to store objects, each one with 65500 bytes)
        • Max allocated: maximum memory allocated.
        To be used in the tweak method.
        See Also:
        Constant Field Values
      • TWEAK_MEM_PROFILER

        public static final int TWEAK_MEM_PROFILER
        Computes the maximum memory in use between two consecutive calls. For example:
         Vm.debug("P Starting profiler for xxxx");
         Vm.tweak(Vm.TWEAK_MEM_PROFILER,true);
         // now run the program during some time
         Vm.tweak(Vm.TWEAK_MEM_PROFILER,false);
         Vm.debug("P Stopping profiler for xxxx");
         
        When it starts, it prints the currently used memory. When you set it off, it will dump the currently used memory (if different of the maximum), and then the maximum memory used between the two calls. For example:
         P Now allocated: 40852408 // printed when turning on
         P Now allocated: 1137060  // printed when turning off
         P Max allocated: 40868844 // printed when turning off
         
        All profiler messages are prefixed with P in the debug console, because it makes easy to filter them. To be used in the tweak method.
        Since:
        TotalCross 1.11
        See Also:
        Constant Field Values
      • TWEAK_DISABLE_GC

        public static final int TWEAK_DISABLE_GC
        Disables the Garbage Collector. This can greatly decrease the time to load some things, but note that you must re-enable it later, otherwise, the system will run out of memory quickly. Example:
         Vm.tweak(TWEAK_DISABLE_GC,true);
         ...
         Vm.tweak(TWEAK_DISABLE_GC,false); // the gc is automatically called here
         
        Since:
        TotalCross 1.14
        See Also:
        Constant Field Values
      • TWEAK_TRACE_CREATED_CLASSOBJS

        public static final int TWEAK_TRACE_CREATED_CLASSOBJS
        This flag turns on the trace of created class objects. This helps you track objects that are not being freed because are held in some way into memory. This tweak increases memory usage, slows down the garbage collector and thus should not be used in production. The output goes to the debug console.
        Since:
        TotalCross 3.1
        See Also:
        Constant Field Values
      • TWEAK_TRACE_LOCKED_OBJS

        public static final int TWEAK_TRACE_LOCKED_OBJS
        This flag turns on the trace of locked objects, which are objects that are locked by the vm and will never be released. This tweak increases memory usage, slows down the garbage collector and thus should not be used in production. The output goes to the debug console.
        Since:
        TotalCross 3.1
        See Also:
        Constant Field Values
      • TWEAK_TRACE_OBJECTS_LEFT_BETWEEN_2_GCS

        public static final int TWEAK_TRACE_OBJECTS_LEFT_BETWEEN_2_GCS
        This flag turns on the trace objects that are left behind between two garbage collector calls. This helps you to find objects that are being held into memory by your program and that are thus never collected. This tweak increases memory usage, slows down the garbage collector and thus should not be used in production. The output goes to the debug console.
        Since:
        TotalCross 3.1
        See Also:
        Constant Field Values
      • TWEAK_TRACE_METHODS

        public static final int TWEAK_TRACE_METHODS
        Enables dump of executed methods to the console. CAUTION: this makes the program slower since hundreds of method calls are sent to the console, use with caution. The output format is: T timestamp thread class - method
        Since:
        TotalCross 3.1
        See Also:
        Constant Field Values
    • Method Detail

      • arrayCopy

        public static boolean arrayCopy​(java.lang.Object srcArray,
                                        int srcStart,
                                        java.lang.Object dstArray,
                                        int dstStart,
                                        int length)
        Copies the elements of one array to another array. This method returns true if the copy is successful. It will return false if the array types are not compatible or if either array is null. If the length parameter would cause the copy to read or write past the end of one of the arrays, an index out of range error will occur. If false is returned then no copying has been performed.
        Parameters:
        srcArray - the array to copy elements from
        srcStart - the starting position in the source array
        dstArray - the array to copy elements to
        dstStart - the starting position in the destination array
        length - the number of elements to copy
        Throws:
        java.lang.ArrayStoreException - If the source array and destination array are not compatible
      • getTimeStamp

        public static int getTimeStamp()
        Returns a time stamp in milliseconds. The time stamp is the time in milliseconds since the program started. The maximum time stamp value is (1 << 30) which represents near 14 days of continuous use, and when it is reached, the timer will reset to 0 and will continue counting from there.
      • setTime

        @Deprecated
        public static void setTime​(Time t)
        Deprecated.
        It won't work on most devices.
        Sets the device time to the given arguments. Note that in some systems, the millis field is ignored. Some devices require that you add Settings.timeZone. Does not work on Android, which does not allow to do this programatically.
        Since:
        TotalCross 1.0
      • exitAndReboot

        public static void exitAndReboot()
        Reboots the device. This is the equivalent of a warm boot (or soft reset). Calling this method terminates the program, closes all open files, calls MainWindow.onExit and, finaly, resets the device.
        The implementation in JDK just exits the program: there's no reboot at all.
        Since:
        SuperWaba 4.01
      • exec

        public static int exec​(java.lang.String command,
                               java.lang.String args,
                               int launchCode,
                               boolean wait)
        Executes a command.

        As an example, the following call could be used to run the command "scandir /p mydir" under Java, Win32 or WinCE:

         int result = Vm.exec("scandir", "/p mydir", 0, true);
         
        The args parameter passed to this method is the arguments string to pass to the program being executed.

        The launchCode parameter was only used under PalmOS. It is no longer used.

        The wait parameter passed to this method determines whether to execute the command asynchronously. If false, then the method will return without waiting for the command to complete execution. If true, the method will wait for the program to finish executing and the return value of the method will be the value returned from the application under Java, Win32 and WinCE.

        To run another TotalCross program from Windows CE devices, use:

         Vm.exec("\\TotalCross\\Path\\Program.exe", null, 0, false);
         
        Here's a sample of how to run the Internet Explorer in Windows CE:
         Vm.exec("\\windows\\iexplore.exe","about:blank",0,false);
         
        You cannot pass null nor "" in the args, or you'll get error 87. IExplore requires a page to open; in this case, we open the blank page. In other words, you must call the program's executable.

        When calling a TotalCross program, you can pass a command line parameter to the calling application, just placing the parameters in the proper argument. It can be retrieved with getCommandLine method from the MainWindow.

        In some platforms, the caller application must be quit by calling exit.

        In Windows 98 and beyond, if you don't pass the full path to the file, it is searched in the current PATH environment variable. The command must contain only the exe name, and all the other arguments must being the args parameter. For example, the following code uses the CMD to open a file with the proper editor:

         Vm.exec("cmd.exe", "/c start C:\\WINNT\\DirectX.log", 0, false);
         
        Important notes about path separators:
        • In the companion we tell to always use / as the path separator. Vm.exec must be used differently of the other places, because you don't pass only paths in the args parameter, pass other things too. So, when you use a path in File, we convert the / to the target separator (\ or /), but in Vm.exec we can't do that, for example, changing "/c start" to "\c start" will make the execution fail. So, you'll have to choose the right separator in the parameters.
        • Make sure that, in Windows, the paths and parameters use \\, not / as path separator, or the command will not run.
        If you're using /cmd and the command fails, change /c option to /k, which will keep the open window instead of closing it, so you can see the error cause.

        In Android, you can launch an application, an url at the browser, execute a shell command, or install an apk:

        • Vm.exec("cmd","logcat -d -f /sdcard/error.log -v time *:I",0,true); -- creates the adb report (useful to get errors - note that you must wait for the file to be created, since the wait parameter does not work - like File f = new File("/sdcard/error.log"); while (!f.exists()) Vm.sleep(500);)
        • Vm.exec("url","http://www.google.com/search?hl=en&source=hp&q=abraham+lincoln",0,true); -- launches a url
        • Vm.exec("url","file:///sdcard/bunny.3gp",0,true); -- launches default app to open the program associated with the 'Video/3gpp' MIME-type passing the URI 'file:///sdcard/bunny.3gp' (see https://gitlab.com/totalcross/TotalCross/issues/61 and https://gitlab.com/totalcross/TotalCross/wikis/Features/open-known-files-in-Android)
        • Vm.exec("url", "googlechrome://navigate?url=" + "file:///storage/emulated/0/BuilderLynx/pics/Page.html", 0, true); -- launches Google Chrome to open 'file:///storage/emulated/0/BuilderLynx/pics/Page.html' (see https://gitlab.com/totalcross/TotalCross/issues/57)
        • Vm.exec("totalcross.app.uigadgets","UIGadgets",0,false); -- launches another TotalCross application
        • Vm.exec("com.android.calculator2","Calculator",0,true); -- runs the Calculator program
        • Vm.exec("/sdcard/myapp.apk",null,0,false); -- calls the apk installation tool. To access the card in Android devices, prefix the path with /sdcard. Be sure that the sdcard is NOT MOUNTED, otherwise your application will not have access to it.
        • Vm.exec("viewer","file:///sdcard/files/chlorine-bogusInfo.txt", 0, true); -- uses an internal viewer to show the txt file to the user (here, stored in the sdcard, but could be anywhere). Also accepts HTML. Also accepts HTML and JPG files.
        • Vm.exec("viewer","/sdcard/Download/handbook.pdf",0,true); -- opens a pdf. Note: you must have a pdf reader installed; search for the free adobe reader in your favorite store. Returns -1 if args is null, -2 if file was not found.
        • Vm.exec("viewer","/sdcard/photo1.jpg",0,true); -- opens a jpeg/jpg/png image so the image can be panned and zoomed. Returns -1 if args is null, -2 if file was not found.
        • Vm.exec("totalcross.appsrvc","TCService",0,true); -- starts the given service
        • Vm.exec("broadcast","broadcast package",flags,true); -- sends a broadcast intent. "flag" is used in intent.addFlags if different of 0.
        • Vm.exec("intent","{\"package\":\"com.company.application\",\"data\":\"file:///sdcard/something.pdf\",\"type\":\"application/pdf\"}",flags,true); -- starts an Intent with given values for package, data and type. The args value is expected to be a valid json object, you may use the class JSONObject to get a valid json string.

        In iOS, the following work as in Android. Note that since iOS does not have a sdcard, you must extract or copy the files to your application's directory (Settings.appPath).

        • Vm.exec("url","http://www.google.com/search?hl=en&source=hp&q=abraham+lincoln",0,true); -- launches a url
        • Vm.exec("viewer",Settings.appPath+"/chlorine-bogusInfo.txt", 0, true); -- uses an internal viewer to show the txt file to the user (here, stored in the sdcard, but could be anywhere). Also accepts HTML. Also accepts HTML and JPG files.
        • Vm.exec("viewer",Settings.appPath+"/handbook.pdf",0,true); -- opens a pdf. WORKS also for XLS, DOC, and all file types that the UIWebView component can show. A PDF reader is NOT required.
        • Vm.exec("viewer",Settings.appPath+"/photo1.jpg",0,true); -- opens a jpeg/jpg/png image so the image can be panned and zoomed.
        In Win32, you can also use the "viewer" or "url" to open files and web pages:
        • Vm.exec("url","http://www.google.com/search?hl=en&source=hp&q=abraham+lincoln",0,true); -- launches a url
        • Vm.exec("viewer","c:\\handbook.pdf",0,true); -- opens a pdf. WORKS also for XLS, DOC, and other registered extensions.
        In Win32 you can find if a program is running by using "running process", and passing the exe's filename (case insensitive):
        • int ret = Vm.exec("running process", "explorer.exe",0,false) == 1;
        To be able to find what's the class name of a program you want to launch, install it in the Android Emulator (which is inside the Android SDK) and run the "Dev Tools" / Package Browser. Then click on the package, and click in the desired Activities button. The command parameter for Vm.exec is the "Process" description, and the args parameter is the activitie's name. Note, however, that there's no guarantee that the program will be available in a real device.

        To install a cab file in Windows Mobile, you can use:

         Vm.exec("wceload.exe", fullPathToCabFile, 0, true);
         
        However, trying to update the program itself or the vm will close the program. So, update it at last.
        Parameters:
        command - the command to execute
        args - command arguments.
        launchCode - no longer used.
        wait - whether to wait for the command to complete execution before returning. If wait is false, don't forget to call the exit method right after this command is called, otherwise the application may not be called. In Android, if you're calling a TotalCross program, the wait parameter is ignored (and defaults to false).
        Returns:
        Usually is 0 if no error occured, or a system error code. -999 means that the file was not found. In Android, is always 0.
      • setAutoOff

        public static void setAutoOff​(boolean enabled)
        Enables or disables device automatic turn-off, which happens after a period of inactivity of the device. If you disable the auto-off, the original auto-off time will be restored automatically when the program exits. Keeping the device always on is desired only when you're working with Sockets. Use it carefully, because it drains the battery.
      • sleep

        public static void sleep​(int millis)
        Causes the VM (or the current thread, if called from it) to pause execution for the given number of milliseconds.
        Parameters:
        millis - time to sleep in milliseconds
      • safeSleep

        public static void safeSleep​(int millis)
        Causes the VM (or the current thread, if called from it) to pause execution for aproximately the given number of milliseconds. This method does not block the user interface engine, as Vm.sleep does, since it keeps calling Window.pumpEvents. So, if you rotate the screen during a Vm.sleep, the rotation is blocked; but during a Vm.safeSleep, the rotation occurs normally. Button presses and other user interface operation also occurs normally during this method. Obviously, if you call Vm.safeSleep(100) and a screen rotation (or any other event) occurs, this method will take to return much more than 100ms. This method only makes sense for sleeps above 500ms, unless you're calling it from a loop (which is reasonable to keep call it), and should not be called from threads.
        Parameters:
        millis - time to sleep in milliseconds
        Since:
        TotalCross 1.3.4
      • vibrate

        public static void vibrate​(int millis)
        Vibrates the device for the specified number of milliseconds. The millis is ignored in iOS, since there's no way to define the duration in that platform.
        Since:
        TotalCross 1.22
      • getFreeMemory

        public static int getFreeMemory()
        Returns the free memory in the device. Returns maximum of 2GB free, even if the device has more than that.
        Since:
        SuperWaba 2.0 beta 4
      • gc

        public static void gc()
        Calls the Garbage Collector. Usually, this isn't necessary; the gc is called everytime theres no more memory to allocate, but you may call it before running a memory-consuming routine.
      • interceptSpecialKeys

        public static void interceptSpecialKeys​(int[] keys)
        Specify which special keys to intercept; use the constants available in SpecialKeys or pass device-specific constants, which can be retrieved calling Vm.showKeyCodes(true). Note that the HOME key cannot be intercepted in Android due to OS restrictions.
        Since:
        TotalCross 1.0
      • isKeyDown

        public static boolean isKeyDown​(int key)
        Gets the current keys being pressed. You must set which keys you want to receive notification with the interceptSpecialKeys method. Note that you can use this method to verify if more than one key is pressed at once, just keep pooling with this method to see when a state has changed. If you just want to intercept the key with a single press, handle it in the onEvent method, with a KeyEvent event.
        Since:
        TotalCross 1.0
        See Also:
        interceptSpecialKeys(int[])
      • debug

        public static void debug​(java.lang.String s)
        Sends a text, preceeded with the current time stamp and followed by a line feed, to:
        • Windows CE / 32: the "DebugConsole.txt" file at the current application's folder
        • Blackberry: the event logger, which can be accessed using alt+LGLG
        • iPhone: the "DebugConsole.txt" file in the application's folder.
        • Java SE: the System.err console
        You can delete the debug memo/txt file passing the ERASE_DEBUG, a constant String declared in this class. E.g.: Vm.debug(Vm.ERASE_DEBUG);.

        Note: if you're debugging a String that contains \0 in it, all chars after the first \0 are ignored.

        See Also:
        Settings.nvfsVolume, disableDebug, ERASE_DEBUG
      • alert

        public static void alert​(java.lang.String s)
        Shows an alert IMMEDIATELY on screen. It uses the sytem message box to show the alert, not the totalcross.ui.MessageBox class.

        Note that unicode characters are not displayed on alerts.
        Since:
        TotalCross 1.0
      • warning

        public static void warning​(java.lang.String s)
        This function can be used to show permanent warnings. It was created because Vm.debug is, in theory, just for debugging. Some TotalCross classes displays warnings to the user, and are not debug (i.e., temporary) messages. It just calls Vm.debug("Warning! "+s), so it differs from it only in a semanthical way.

        Note: you cannot use this function with ERASE_DEBUG; it won't work.

        Since:
        SuperWaba 4.21
      • clipboardCopy

        public static void clipboardCopy​(java.lang.String s)
        Copies the specific string to the clipboard.
      • clipboardPaste

        public static java.lang.String clipboardPaste()
        Gets the last string from the clipboard. if none, returns "".
      • attachLibrary

        @Deprecated
        public static boolean attachLibrary​(java.lang.String name)
        Deprecated.
        This method never worked in TotalCross. Previously, in SuperWaba, all class and resources were placed in a PDB file, so attaching a pdb file was ok. However, in TotalCross, everything is placed in TCZ files, so attaching a PDB is useless. To load an image that you saved with Image.saveTo, use Image.loadFrom.
        Attaches a library to this application instance. TotalCross libraries are files that have a Lib suffix.

        This method is useful if you have a library and want to make its classes available to your app. At the initialization, TotalCross scans all libraries in the device and automatically attach them. However, if you downloaded a new library from a server or saved a bitmap into a file, you will need to attach the file where it is located so you can instantiate its classes or load the image using new Image(filename).

        After a library is added, its file is blocked and thus cannot be modified.

        To see what libraries are in the device, you can use PDBFile.listPDBFiles or File.listFiles and check the files that ends with Lib

        A check is made to prevent a library from being loaded twice.

        Parameters:
        name - the library's name, with a 'Lib' suffix. Cannot contain a creator neither a type.
        Returns:
        true if the library was found and attached, false otherwise.
        See Also:
        Image.loadFrom(totalcross.io.PDBFile, java.lang.String)
      • attachNativeLibrary

        public static boolean attachNativeLibrary​(java.lang.String name)
        Attaches a native library to this application instance (only works at device). You must attach the native library before use any native methods from your library, otherwise you'll get errors like "cannot find native method implementation for ...". To learn how to create a native library, look at the Library Tutorial chapter. In desktop, always returns true. A check is made to prevent a library from being loaded twice.

        Does not work on Android.
        Parameters:
        name - the library's name. The suffix 'Lib' is not mandatory. Cannot contain a creator neither a type.
      • getFile

        public static byte[] getFile​(java.lang.String name)
        Returns a byte array of a file contained in the same tcz where this one resides, or in some attached library (or JAR, if application is running in a browser). The returned array is a fake pointer; does NOT point directly to the file (a new buffer is created to store the contents). Example:
         byte[] b = Vm.getFile("textfiles/About.txt");
         if (b != null)
            new MessageBox("About", new String(b, 0, b.length)).popup();
         
        The TotalCross deployer will insert the .txt file into the program's tcz/pdb.
        Parameters:
        name - The name of the file, exactly as shown by tc.Deploy in the output window. In desktop it is case insensitive, while in device it is CASE SENSITIVE.
        Returns:
        a byte array with the file or null if file not found
      • getRemainingBattery

        public static int getRemainingBattery()
        Returns the percentage of the remaining battery life of this device. In systems that can have an auxiliary battery, it will return the sum of the main and the auxiliary battery, but this sum will always be limited to 100%. In desktop, it will always return 100. Note that in some OSes, when on the cradle, the returned value may be 100% even when charging.
        Since:
        SuperWaba 4.21
      • tweak

        public static void tweak​(int param,
                                 boolean set)
        Tweak some parameters of the virtual machine. Note that these parameters are only available at the device, NOT when running as Java. Also, the configuration is not persisted: you must set this every time you run the program. Each tweak must be made separately; they are NOT bit masks. For example:
         Vm.tweak(Vm.TWEAK_AUDIBLE_GC,true);
         Vm.tweak(Vm.TWEAK_DUMP_MEM_STATS,true);
         
        Since:
        SuperWaba 5.82
        See Also:
        TWEAK_AUDIBLE_GC, TWEAK_DUMP_MEM_STATS, TWEAK_MEM_PROFILER
      • getStackTrace

        public static java.lang.String getStackTrace​(java.lang.Throwable t)
        Returns the given throwable stack trace as a String. A good alternative to show an exception to the user is:
         try
         {
            ...
         }
         catch (Exception e)
         {
            MessageBox.showException(e, false); // last parameter dumps to the console if true
         }
         
        Since:
        SuperWaba 5.82
      • getStackTrace

        public static java.lang.String getStackTrace()
        A shortcut for try {throw new Exception();} catch (Exception e) {return getStackTrace(e);}
      • showKeyCodes

        public static void showKeyCodes​(boolean on)
        Set to true to popup an alert for each key pressed. This is useful for you to discover key codes that may be intercepted with Vm.interceptSpecialKeys. Note that this will probably block the application and you will have to provide a button to exit from it or just reset the device.

        On Windows CE, the key 91 is always displayed when a hotkey is pressed, so the vm will silently ignore it.
        Since:
        TotalCross 1.0
      • turnScreenOn

        public static boolean turnScreenOn​(boolean on)
        Turns the screen on or off, but keeps the device running. This greatly improves battery performance.
        Returns:
        If the method succeed.
        Since:
        TotalCross 1.15
      • printStackTrace

        public static void printStackTrace()
        Prints the stack trace to the debug console file. Implemented as:
              try 
              {
                 throw new Exception("Stack trace");
              } 
              catch (Exception e) 
              {
                 e.printStackTrace();
              }
         
        Since:
        TotalCross 1.3
      • printStackTrace

        public static void printStackTrace​(java.lang.String msg)
        Prints the stack trace to the debug console file with the given message.
      • preallocateArray

        public static void preallocateArray​(java.lang.Object sample,
                                            int length)
        This method pre-allocates space for an array of objects with the given length. It can reduce the number of calls to GC when allocating big arrays. If the total size (Object size * length) is small, calling this method is useless and will not result in any performance gain. You can always measure how the gc affects your program by doing this:
         int gcc = Settings.gcCount, gct = Settings.gcTime, ini = Vm.getTimeStamp();
         ... run some memory-consuming routine
         Vm.debug("gcCount: "+(Settings.gcCount-gcc)+" ("+(Settings.gcTime-gct)+"ms), elapsed: "+(Vm.getTimeStamp()-ini)+"ms");
         
        This is a sample that pre-allocates space for a ListContainer, taken from the PopupMenu class:
         Vm.preallocateArray(new ListContainer.Item(layout), itemCount);
         
        This method does nothing under Blackberry and Java SE.
        Since:
        TotalCross 1.5
      • identityHashCode

        public static int identityHashCode​(java.lang.Object object)
        Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode(). The hash code for the null reference is zero.
        Parameters:
        object - Object for which the hash code is to be calculated.
        Returns:
        The desired hash code.