- HOWTO: Running Java code directly on Android (without creating an APK)
- A (not so) simple Hello World program
- Setting up the working directory
- Compiling and dexing the Java class
- Creating the startup shellscript
- Installing and running the (non-) app
- It works, but how do I get a Context?!
- Запускаем консольные Java приложения на Android
- Virtual Machine in Android: Everything you need to know
- Virtual Machine?
- Java Virtual Machine
- How it works?
- Android OS
- Why Android use virtual machine?
- Dalvik Virtual Machine
- Dalvik EXecutable
- Compare with Java VM
- Android Runtime
- Just-In-Time vs Ahead-Of-Time
- Compare with Dalvik VM
- Optimized Garbage Collector
- In Conclusion
- How to Use Android Studio to Write Pure Java
- Here’s How
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.
Источник
Запускаем консольные Java приложения на Android
Речь пойдёт о проекте-утилитке, который может пригодиться всякому кто изучает Java и не всегда имеет под рукой ПК для просмотра работы примера кода в полевых условиях (как-то — в метро, маршрутке, кафешке и т.д.).
Необходимость создать сие поделище возникла когда я готовился к OCJP-сертификации. После успешного прохождения оной, решил предоставить плоды своих задумок на обозрение уважаемым участникам хабрасообщества.
Ноутбука у меня нет, а запускать примеры кода на смартфоне, сидя на кухне за чашечкой чая, удобно.
Так уж повелось, что бо́льшая часть примеров для обучения обычно приводится именно в формате консольных программ. Замечательный инструмент AIDE позволяет собирать Android-приложение на основе Eclipse-проектов. Возможность, увы, недостаточная для запуска консольных примеров методом копипасты.
Дело за малым — перенаправляем потоки ввода/вывода в UI контролы:
Консольная программа стартует в отдельном потоке из обработчика activity onResume() :
Здесь же можно задавать аргументы командной строки — старый добрый args . Пример — запуск BankTellerSimulation на 10 секунд:
Поддерживается работа нескольких потоков ( SimpleThreadsTest ):
HorseRace и BankTellerSimulation — примеры более сложных многопоточных приложений (взяты из книги Thinking in Java, 4th Ed by Bruce Eckel).
Ошибки времени выполнения
Напоследок, для полноты возможностей, был добавлен консольный ввод. Пока что мои познания в области пользовательского интерфейса Android не велики. Кое-как впихнуть EditText удалось, но результат не идеален 🙂
Приглашение ввода строки ( ReadingInputTest ):
Функции меню
Exit выключает процесс через System.exit(0) .
Программа «одноразовая». Повторных перезапусков нет (не хотелось возиться с очисткой значений статических полей).
Что делает Clear — большой секрет.
Что не работает
• assert ‘ы Java. Т.е. оператор
исключение java.lang.AssertionError не кинет. Не путать с assert’ами JUnit — с ними всё в порядке!)
• Класс Console .
• Поле ввода не всегда подхватывает фокус.
Файлы проекта
Исходники можно забрать с GitHub, либо скачать zip-архив с проектами для Android Studio и Eclipse.
Источник
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.
Источник
How to Use Android Studio to Write Pure Java
Feb 19, 2016 · 3 min read
For those looking to sharpen skills using Data Structures and building Algorithms you’re most likely reading Cracking The Code Interview as well doing practice problems on a number of the sites out there (KhanAcademy, HackerRank, InterviewCake, coderbyte, , GeeksforGeeks, etc…)
I prefer using one compiler to do everything, and since I’m developing apps in Android Studio I’d like to also construct my coding challenge here because…
- Some coding challenge sites / classes pick a specific language and I want to use Java or I’m doing questions out of a book.
- I can automatically save my solution for referring back in a Google Drive folder as well as on GitHub through the Android Studio UI.
Before I show you how, if you want to get running right away you can download or fork this example Repo and you won’t need to read further. If you plan to upload it to a type of Version Control just make sure to remove the origin and replace it with your Repo using this command in the terminal: git remote set-url origin git@github.com:yourprofilename-/RepoName.git
Here’s How
- Open a new Project and choose your Destination path and initial settings: Hit Next on Form Factors (doesn’t matter) > Choose No Activity and Finish
- In the dropdown view Select Project
3. Remove app Directory and in Settings.gradle delete include ‘:app’ > ignore the Sync Now prompt at the top of the screen in Android Studio
4. Replace build.gradle code with the following > Then click Sync Now prompt
5. Configure src and Child Directories main , java , foo and .java Class > Add in main class to construct code and print results
6. Configure Android Studio to run your Java Class properly: Edit Configurations > ‘+’ > Application
Источник