Munchausen style, or one crazy way to run Java programs on Android

    image

    One fine day, I was overcome by a strange desire - to use the full power of my android smartphone in the console. A very convenient way for all sorts of utilitarian tasks. In the console, this is the key point of my story.
    As such, development for Android (if we are talking about the standard Android SDK, not the NDK) does not imply console programming. Activity, services, intentions - in general, not a dozen articles have been written on this topic, but mine is about another.

    As you may know (or maybe not), Android programs, although written in Java, must be converted to completely different byte code from Java before execution. Because the Dalvik virtual machine, the heart of Android, is organized differently than the Java SE VM. To do this, use a special utility as part of the Android SDK called dx (Dalvik eXecutable).
    It works devilishly simply:
    java -jar dx.jar --dex --output=dexed.jar java.jar
    

    where java.jar is a java package with java classes, and dexed.jar is a java package suitable for uploading and running on Android.

    What to do if you really want to run some kind of console dzharik directly "in the field"? The conclusion suggests itself - convert dx.jar using itself, upload it to the device, and use it right there. The idea, of course, is risky, but we will try.
    java -jar dx.jar --dex --output=dx.apk dx.jar
    adb push dx.apk /sdcard/dx.apk
    adb push helloworld.jar /sdcard/helloworld.jar
    


    here I will take a short pause to give some clarification.
    Although the Android SDK does not imply the development of console programs, Dalvik calmly launches and runs them. Naturally, you must do this in some terminal program. Dalvik has one more nuisance - it does not support the -jar option. Well, that is, the option itself is, but he ignores it. At least for my Milestone 2 with Android 2.3.4 this is true. Therefore, the package with the program must be specified with the -cp switch, and the main class to be launched with the main method is manually.
    adb shell
    cd /sdcard
    dalvikvm -cp dx.apk com.android.dx.command.Main --dex --output=helloworld.apk helloworld.jar
    dalvikvm -cp helloworld.apk helloworld.Main hello
    Hello, hello!
    


    So, if you have a “dexed” dx, you can run java-programs directly on the device.
    I hope this information was useful to you, habrauser.

    Happy New Year!

    Also popular now: