Run any java program on android

HOWTO: Running Java code directly on Android (without creating an APK)

A step by step instruction for compiling a Java program into Android executable and using ADB to run it.

When you want to create a system / commandline tool for Android, you have to write it in C(++)… or do you?

TLDR; here’s the final proof of concept.

Sticking with Java would have the benefit of avoiding all of the native ABI hassle and also being able to call into the Android runtime. So how do we do that?

A (not so) simple Hello World program

Let’s start with the Java program we want to run. In order to make it a bit more interesting (and because any useful program has dependencies), it won’t just print the obligatory “Hello World” message, but also use the Apache Commons CLI library to parse its commandline arguments:

Setting up the working directory

We will have to manually run several commandline tools in the next step, assuming the following final directory structure:

Start by creating an empty directory in a convenient place. Download and unpack the following items there:

  • Android SDK (either via Android Studio or the SDK Manager). NOTE: If you are an Android developer, you’ll have the Android SDK already installed. In that case, you don’t actually need to copy it to the working directory as long as you know the path to the dx tool.
  • Apache Commons CLI library v1.3.1

Afterwards copy&paste the HelloWorld code from above into the source folder. You might also find my semantic version parser class useful later on (not required here, though).

Compiling and dexing the Java class

Next step is to compile the java class (keep in mind that Android is stuck with Java 7 — bytecode for later versions won’t work). In case you are not used to doing this outside of an IDE, here’s the command:

Make sure the program compiled properly:

Android cannot run Java class files directly. They have to be converted to Dalvik’s DEX format first (yes, even if you are using ART):

NOTE: Android Build Tools v28.0.2 and later contain a dx upgrade, called d8 . The d8 tool can process Java 8 class files. I’ll stick with dx for backwards compatibility reasons here.

Creating the startup shellscript

Android does not have a (normal) JRE, so JAR files cannot be started the same way as on a PC. You need a shellscript wrapper to do this. Copy&paste the one below to the workspace.

NOTE: DEX files can also be started directly using the dalvikvm command, but going through app_process gives us a pre-warmed VM from the Zygote process (it is also the method employed by framework commands like pm and am ).

Installing and running the (non-) app

Time to push everything to the device:

Moment of truth (fingers crossed):

NOTE: Since nothing was installed into the system, getting rid of the program is simply done by deleting the directory again.

It works, but how do I get a Context?!

Contexts represent an environment that is associated with an app (which we explicitly did not build) and are also device dependant. They can only be created by the ActivityThread class (a hidden system class that you cannot instantiate). If you want to interact with the Android runtime, you have to talk to the system services directly through their Binder interfaces. But that’s a topic for another article.

Читайте также:  Android не подключается аккаунт

Источник

Top 9 Android Apps and IDE for Java Coders and Programmers

December 11, 2014 4 min read

Recently at IDRsolutions my colleagues have spent a lot of time traveling to different conferences such as Oracle Code One and DevFest. One of the complaints my colleagues have is the amount of luggage they have to carry, especially when they still want to work on code for our Java PDF Viewer and SDK, PDF to HTML5 converter and a Java ImageIO replacement.

Having previously written an article on the ‘The 10 Best Android Apps for Designers and Web Developers’ as I spend a lot of my time on the web development and designing side of things, it occurred to me that Android is an extremely powerful platform (and open source) and I would be sure to find useful Apps and IDE’s for Java Coders and Programmers.

So to help make things easier for them, and with my keen interest in technology and love of gadgets, I grabbed my trusty Android phone to see what I could find.

JavaIDEdroid

JavaIDEdroid is an IDE (integrated development environment) that can run on Android and allows you to natively create Android applications without the need to use the Android SDK on Mac, Windows or Linux. JavaIDEdroid comes equipped with an aapt tool, compiler for Java, dx tool, DexMerger tool, ApkBuilder, zipsigner-lib (this library also does the zipalign), SpongyCastle Library, BeanShell Interpreter and JavaRunner, which allows running of any binary Java command line applications (.jar file).

Java Editor

Java Editor is a very easy-to-use and simple Java editor. It’s limited in functionality but it can color the syntax nodes, attributes, properties, events and also supports auto-completion and search and replace. It can open default files with the extensions jav & java.

DroidEdit

DroidEdit is a text and source code editor (similar to Notepad++ on the PC) and is available for android tablets and phones. DroidEdit is supported by android tablets with external keyboards like the Asus Transformer or those with third-party external keyboards, there is also support for Hackers Keyboard. It also supports a variety of languages like C, C++, C#, Java, HTML, CSS, Javascript, Python, Ruby, Lua, LaTeX, and SQL.

There is also a premium version with SFTP/FTP, Dropbox, Drive and Box support (great if you are on the move), custom themes (for those that want to customize everything), external commands through SSH and root mode.

Dcoder

Dcoder is a mobile coding IDE that is designed to help you learn to programme. It supports over 30 programming languages, including Java, C, C++, Python, C#, PHP and Ruby. It has a Rich Text Editor which has syntax highlighting, some autocomplete features and undo/redo. It also comes with algorithm problems for you to solve, to help you learn.

Code Peeker Pro: Source Reader

Code Peeker Pro comes with syntax highlighting and allows you to look up snippets. Although not an editor, it is a useful code reader and has been selected to be part of the Google Play for Education program and is currently used in schools as a teaching aid. Code Peeker will open and highlight any supported code language like C/C++ (c, cc, CPP, h, hpp), C# (c-sharp, csharp, cs), CSS, Java, JavaScript (js, JScript), PHP, Python (py), Ruby (rails, ror), XML (XML, XAML, XSLT, HTML, XHTML), ActionScript 3 (as3), AppleScript, Cold Fusion, Delphi/Pascal, Diff/patch files, Erlang, Groovy, JavaFX (jfx), Perl (pl), PowerShell (ps), Sass, Scala, SQL, Terminal scripts (bash, shell, sh, RC, conf), Visual Basics (vb, vbnet) and Verilog & System Verilog (v, SV)

It can also mark where the important code is, comes with a built-in file browser (in case your phone doesn’t have one), supports internal and external SD card memory and also supports other file browsers (Dropbox, File Expert, FX, Astro File Manager, etc).

AIDE – Android IDE

AIDE is an integrated development environment (IDE) for developing real Android apps directly on your Android device. It comes with interactive coding lessons and step-by-step tutorials for app development and Java programming skills. You can visually design apps, write code with the editor which can do code completion, real-time error checking, refactoring, smart code navigation and more.

Читайте также:  Орт виджет часов для андроида

AIDE supports Java/Xml and the Android SDK, apps with C/C++ and the Android NDK as well as pure Java console applications. AIDE is fully compatible with Dropbox and allows easy download of your code from your Dropbox and sync back your changes. AIDE can also open Android Studio projects which follow the default folder structure. AIDE also supports Git for professional development.

Anacode IDE

Anacode is another IDE (integrated development environment) and source code editor that supports the languages Java, HTML, CSS, PHP, JavaScript and C/C++ and allows you to build and run from your android device.
You can also write and test HTML, JavaScript and CSS in the built-in or system browser, upload to FTP and support the Tasks list too.

Quoda Code Editor

Quoda is easy to use source code editor or IDE, similar to Notepad++, with support for SFTP/FTP(S) servers and cloud storage (Dropbox and Google Drive). Some of the features include syntax highlighting with themes, cross-session editing, code-completion, extended keyboard, downloading source code from URL, auto-encoding detection, brace matching, auto-indentation, line bookmarking, colour picker, HTML formatting and more. These features come at a premium though and you may have to pay extra for newer or additional features. There is support for the following programming languages which include: ActionScript, C, C++, C#, CSS, Haskell, HTML, Java, JavaScript, Lisp, Lua, Markdown, Objective-C, Perl, PHP, Python, Ruby, SQL, Visual Basic and XML.

Java N-IDE

Java N-IDE was created to help people learn Java. It is a lightweight IDE that only supports Java. However, it does come with an offline compiler, autocomplete and code formatter. It is an open-source IDE with more features currently being worked on.

Hopefully, this guide has given you some useful ideas of what editors and IDEs you can use if you are on the go and also gives you a bigger insight into what your Android phone/tablet can do in terms of coding/programming.

Do you use your Android Phone or Tablet in a similar way? Let us know what apps you use.

If you are interested in IDE articles take a look at:

We now have a series of articles on what is new in Java 9:

Источник

Virtual Machine in Android: Everything you need to know

Aug 4, 2019 · 6 min read

Virtual Machine?

A virtual machine is based on computer architectures to provide functionality of a computer.

There are 2 main types of Virtual Machine (VM):

  • System virtual machines (full virtualization VMs) provide a substitute for a real machine.
  • Process virtual machines are designed to execute computer programs in a platform-independent environment.

Java Virtual Machine

Follow “write once, run anywhere” principle, JVM allows programs — written in Java/Kotlin — to run on any device or operating system.

How it works?

IDEs — like IntelliJ / Android Studio — use Java Compiler ( javac ) to compile Java code ( .java ) into Java bytecode ( .class ).

Then on runtime environments (Web, PC, Android), JVM translates it into machine specs instruction set that this environment can understand.

  • Start JVM.
  • Start main thread. Load .class into memory using Classloader.
  • Verify bytecode is valid and not violate Java’s security restrictions.
  • Translate bytecode into machine instructions and execute them.
  • Unload classes. Terminate main thread.
  • Shutdown JVM.

Note that: It’s possible to compile Java code to native code ahead-of-time, then run. And it’s also possible to interpret Java code directly.

Android OS

Android is an open source, Linux-based software stack created for a wide array of devices and form factors. For example, the Android Runtime (ART) relies on the Linux kernel for underlying functionalities: networking, multi-threading and low-level memory management.

Why Android use virtual machine?

There are many reason that Google engineers decide to use Android with VM, but two main reason is:

  • Security: In theory, app code is totally isolated by the VM and cannot even “see” the host OS. So app code that contains malware cannot affect system directly, make app and system more robust and reliable.
  • Platform independent: Android platform can run on different devices with different architectures (ARM, MIPs, x86). To abstract out the need to compile binaries for each architecture, VM comes into play.
Читайте также:  Громкость звука андроид инженерное меню

Dalvik Virtual Machine

Dalvik Virtual Machine (DVM) is a Process virtual machine for Android.

DVM is a virtual machine that optimized for mobile environment (memory, battery life, performance. )

Dalvik EXecutable

Dalvik EXecutable ( .dex ) is Dalvik bytecode which translated from Java bytecode using dx tool (replaced by D8 tool since API 28). This format was designed for systems that have constrained memory and processor speed.

Multiple classes are included in a single .dex file:

Compare with Java VM

The DVM was built specifically for Android, to address the battery life, processing speed. Moreover, the Java tools are free but the JVM is not, so Google engineers made their own VM and made it as free.

Unlike JVM, which are simple stack machines, the DVM uses a register-based — which requires fewer instructions, fewer code units, avoid unnecessary memory access — resulting in better performance code.

Android Runtime

Android Runtime (ART) is the managed runtime used by apps and system services on Android. Replacing the predecessor Dalvik, ART performs the translation of the app’s bytecode into native instructions that are later executed by the device’s runtime environment.

The ART is written to run multiple VMs on low-memory devices. To maintain backward compatibility, ART also uses the same input bytecode as Dalvik — the standard Dalvik EXecutable ( .dex ) files — which also designed for Android to minimize memory footprint.

From Android 5.0, each app runs in its own process, with its own instance of ART. But prior to this, it use Dalvik. If your app runs well on ART, then it should work on Dalvik as well, but the reverse may not true.

Just-In-Time vs Ahead-Of-Time

Just-In-Time (JIT) added in Android 2.2. It dynamically compiles bytecode into native machine code at run-time to make app runs faster. It does all this while app is running, and that’s where the “Just-In-Time” comes from.

Ahead-Of-Time (AOT) added in Android 4.4. It statically compiles bytecode into machine code at install-time — using on-device dex2oat tool — and stores data in the device’s storage, to improve run-time performance.

Compare with Dalvik VM

Dalvik is a JIT compilation based engine.

The ART includes a JIT compiler (with code profiling). The JIT compiler complements new AOT compiler and improves runtime performance, speed up apps and system updates.

Furthermore, ART has many more advantage:

  • Optimized garbage collector: one GC pause instead of two.
  • Loop optimizations: Bounds check, Induction variable is eliminated.
  • Faster native calls using @FastNative and @CriticalNative annotations.
  • Improve battery life.
  • Reduce startup time as native code is directly executed.
  • Faster runtime performance because AOT compile at install-time.
  • From API 28, convert APK’s DEX files to more compact machine code.
  • Better debugging support (dedicated sampling profiler, detailed exceptions reporting, and ability to set watchpoints to specific fields).

Optimized Garbage Collector

Garbage Collector (GC) can impact app’s performance with “stop-the-world” events, which resulting in frozen frames, poor UI responsiveness. The default GC plan is the CMS (concurrent mark sweep).

The ART improves GC in several ways:

  • The number of pauses is reduced from 2 to 1 compared to Dalvik. Dalvik’s first pause — which mostly root Marking — is done concurrently in ART by getting the threads to mark their own roots.
  • Parallelized processing in the second pause (before Sweeping phase).
  • Increased GC throughput enabled by the sticky CMS collector.
  • Reduce total time when clean up recently-allocated, short-lived objects.
  • Performs heap compaction — when app changes process state to background or cached — to reduce background memory usage.

In Conclusion

Before Android 5.0 (API 21), Android use Dalvik Virtual Machine (DVM) — a Process virtual machine — that optimized for mobile environment (memory, battery life, performance. ).

After that, each Android app runs in its own process and with its own instance of the Android Runtime (ART) — an app runtime environment used by Android OS. Replacing Dalvik, ART performs the translation of the app’s bytecode into native instructions that are later executed by the device’s runtime environment.

Источник

Оцените статью