Android running java programs

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.

Читайте также:  Визуальная новелла романтика андроид

Источник

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)

Читайте также:  Android studio handler deprecated

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 running java programs

Сегодня речь пойдет о том, как запускать полноценные java-приложения на устройствах под управлением Android, для чего это может быть необходимо и какие приложения будут актуальны для мобильной платформы. Полноценные приложения это те, для запуска которых не хватает возможностей Dalvik VM. Таким приложениям необходима JRE. Далее поговорим о том, как ее установить и работать с ней.

Установка

Для установки JRE требуется установить какой-нибудь terminal и busybox. Последний пакет требует наличия root-прав. О том, как получить root-права для Android можно прочесть здесь. Сама JRE не требует root. Скачать приложение можно из основного репозитория альтернативного маркета F-droid, либо самостоятельно собрать пакет из исходного кода. Сам процесс установки тривиален, все как и для любого другого apk-файла. После запуска программы она предложит докачать дополнительные библиотеки (glibc, awt и т.д.). Кстати, все зависимости, вроде терминала и busybox программа также способна скачать самостоятельно. Разумеется, для максимальной совместимости необходимо отметить все элементы.

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

Использование

Для запуска jar-архива нажимаем на кнопку «run jar file», программа запрашивает доступ к файловой системе. Выбираем программу, с помощью которой указываем файл для запуска.

Лично я рекомендую Total Commander в качестве файлового менеджера. Он бесплатен и очень удобен, плюс есть поддержка плагинов.

Так вот, после выбора файла открывается окно терминала, который запускает java-машину и передает ей путь к выбранному jar-файлу. Далее, в зависимости от программы, работа будет через терминал, либо запустится отрисовка интерфейса. Очень легко и удобно, не правда ли? К сожалению, есть небольшой косметический недочет, при первом запуске в терминале криво отображается путь к исполняемому файлу java и передаваемым аргументам.

Но на работу это не влияет, а при повторном запуске команды она отображается правильно.

На рисунке результат запуска небольшого тестового проекта. Его код приведен ниже

Что касается GUI-приложений, то мой AExplorer отказался запускаться, ссылаясь на отсутствие поддержки в текущих версиях.

Тем не менее, «полноценные» консольные приложения работают без особых проблем.

Итоги

Не смотря на очевидные недоработки в запуске оконных приложений, на сегодняшний день уже возможно запускать консольные java-приложения. Они работают без каких-либо проблем, если не используют каких-либо дополнительных нативных библиотек. В таком случае необходимо сначала собрать библиотеку на устройстве, а уже потом запускать jar-архив. Тем не менее, java installer на сегодняшний день вполне жизнеспособный проект.

Источник

Запускаем консольные 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.

Источник

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