- 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
- Top 9 Android Apps and IDE for Java Coders and Programmers
- JavaIDEdroid
- Java Editor
- DroidEdit
- Dcoder
- Code Peeker Pro: Source Reader
- AIDE – Android IDE
- Anacode IDE
- Quoda Code Editor
- Java N-IDE
- Android run java tool
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.
Источник
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:
Источник
Android run java tool
Краткое описание:
Работа с java
##О приложении
Этот проект создан для изучения и создания Java приложений на Android.
Вы можете создать и запустить Ява-приложение с JDK 1.7.
(НЕт оффициальной поддержки) Создайте apk-файл (поддержка только armeabi-v7a, x86, x86_64)
## Туториалы(Советы по использованию)
1. Настройте систему https://youtu.be/FZtSbgq8ZN0
2. Создайте файл при помощи библиотеки https://youtu.be/fUFqR8ZlChg
3. Создайте Android приложение https://youtu.be/euZilR8-EhA
##Внимание
Это бета версия,которая будет часто обновляться.
## Todo(. Оставлено по английски,иначе будет утрачен смысл.
1. Java compiler JDK 1.7 ✔
2. Java editor ✔
3. Java auto complete code ✔ (But not working perfect)
4. Java debugger (jdb).
5. Run java file, class file ✔
6. Build java library ✔
7. Support VCS
8. Decompile class, jar
9. Java code formatter (Google Java code formatter) ✔
10. Build Android app. ✔
11. XML auto complete
12. Layout builder for Android
## Что содержит проект?
1. Javac — Java compiler
2. Aapt — Android asset package tool
3. Dx — Dex for dalvik vm
4. Zip Signer
5. Apk сборщик
Это приложение бесплатно, потому что я хочу помочь людям изучать Java. Я работаю для людей. Если вы хотите поддержать проект нажмите на кнопку Донат в приложении.
## Overview
This project is develop to help the community learn java on android.
You can build and run Java file with JDK 1.7.
(No official support) Build apk file (only support armeabi-v7a, x86, x86_64)
##Attention
Because this is beta version so I will update very often.
## Todo
1. Java compiler JDK 1.7 ✔
2. Java editor ✔
3. Java auto complete code ✔ (But not working perfect)
4. Java debugger (jdb).
5. Run java file, class file ✔
6. Build java library ✔
7. Support VCS
8. Decompile class, jar
9. Java code formatter (Google Java code formatter) ✔
10. Build Android app. ✔
11. XML auto complete
12. Layout builder for Android
## What does tools the project include?
1. Javac — Java compiler
2. Aapt — Android asset package tool
3. Dx — Dex for dalvik vm
4. Zip Signer
5. Apk builder
## Contribute
I would absolutely love every possible kind of contributions. If you
have a questions, ideas, need help or want to propose a change just open
an issue. Pull request are greatly appreciated.
This app is free for everyone to learn Java. I work for the community. If you want to donate to the project, you can click donate button in the application.
Источник