On an Android device, the Dalvik virtual machine usually executes embedded in the Android application framework. It's also possible to run it directly, just as you would a virtual machine on your desktop system.
After compiling your Java language sources, convert and combine the .class files into a DEX file, and push that to the device. Here's a simple example:
% echo 'class Foo {'\
> 'public static void main(String[] args) {'\
> 'System.out.println("Hello, world"); }}' > Foo.java
% javac Foo.java
% dx --dex --output=foo.jar Foo.class
% adb push foo.jar /sdcard
% adb shell dalvikvm -cp /sdcard/foo.jar Foo
Hello, world
The -cp
option sets the classpath. The initial directory
for adb shell
may not be what you expect it to be, so it's
usually best to specify absolute pathnames.
The dx
command accepts lists of individual class files,
directories, or Jar archives. When the --output
filename
ends with .jar
, .zip
, or .apk
,
a file called classes.dex
is created and stored inside the
archive.
Run adb shell dalvikvm -help
to see a list of command-line
options.
You can debug stand-alone applications with any JDWP-compliant debugger. There are two basic approaches.
The first way is to connect directly through TCP. Add, to the "dalvikvm" invocation line above, an argument like:
-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=y
This tells the VM to wait for a debugger to connect to it on TCP port 8000. You need to tell adb to forward local port 8000 to device port 8000:
% adb forward tcp:8000 tcp:8000
and then connect to it with your favorite debugger (using jdb
as an example here):
% jdb -attach localhost:8000
When the debugger attaches, the VM will be in a suspended state. You can set breakpoints and then tell it to continue.
You can also connect through DDMS, like you would for an Android application. Add, to the "dalvikvm" command line:
-agentlib:jdwp=transport=dt_android_adb,suspend=y,server=y
Note the transport
has changed, and you no longer need to
specify a TCP port number. When your application starts, it will appear
in DDMS, with "?" as the application name. Select it in DDMS, and connect
to it as usual, e.g.:
% jdb -attach localhost:8700
Because command-line applications don't include the client-side DDM setup, features like thread monitoring and allocation tracking will not be available in DDMS. It's strictly a debugger pass-through in this mode.
See Dalvik Debugger Support for more information about using debuggers with Dalvik.
Copyright © 2009 The Android Open Source Project