- Run java exe on android
- Установка
- Использование
- Итоги
- 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?!
- Run java exe on android
- Here’s how to open exe files on your Android phone
- Open with Inno Setup Extractor
- Run exe files on Android with a DOS BOX app
- Запускаем консольные Java приложения на Android
Run java exe on android
Сегодня речь пойдет о том, как запускать полноценные 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 на сегодняшний день вполне жизнеспособный проект.
Источник
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.
Источник
Run java exe on android
Краткое описание:
Работа с 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.
Источник
Here’s how to open exe files on your Android phone
You would be wrong if you thought exe files only work on Windows machines. If you own a current Android smartphone or tablet, you can run at least some of them. The bad news is that you cannot directly download and install an exe file on the Android OS. The good news is that you can get an exe file opener for Android, along with an exe run app, that can help you out.
You may be asking why you would even want to run an exe file on Android. The biggest reason is for playing older Windows games that have not yet been ported over to the Android OS. Using an emulator can also solve that issue, and it might even be a more straightforward solution, but running exe files on Android might still be a worthy project to some.
Many apps will open exe files on Android. Keep in mind that not all exe files will run on Android, even with these special apps. If you were thinking about running Doom Eternal, that’s not going to happen. However, if you want to run the 1993 Windows version of Doom, these exe file openers for Android could be the perfect solution.
With that out of the way, here’s how to run exe files on Android!
Editor’s note: Android doesn’t officially support exe files. You are likely to encounter roadblocks such as bugs, compatibility issues, and more. Do this at your own risk, and make sure you know what you’re doing before tinkering with your phone.
Open with Inno Setup Extractor
Inno Setup Extractor is perhaps the easiest exe file opener to use. After you download your desired exe on your Android phone, download and install Inno Setup Extractor from the Google Play Store, use a file browser to locate the exe file, and open that file with the app. Inno Setup Extractor will then extract the exe on your Android phone, and you can check out those files afterward.
Run exe files on Android with a DOS BOX app
If you have any experience running older programs on more recent operating systems, you are likely aware of DOS BOX applications. They allow programs made for the old MS-DOS system to work on, say, Windows 10 via emulation. The good news is that there are also DOS BOX apps for Android.
One of the easiest to use is AFreeBox. If you have installed this app on your Android phone, you might be able to open some exe files. To do that, place the exe file you want to use in a new folder on your device and name it (any name is OK, just make it easy to remember). Then run AFreeBox, and then type in “cd\folder name” into the command line. Once you are inside that folder, type in the name of the exe file in the command line. If the program is compatible with the AFreeBox app, the exe file should run on your Android product.
While there are ways for exe files to run on your Android phone, we will once again point out that not all exe programs can be run on your new device, even if it has the highest-end hardware specs. Still, it’s a possible solution worth exploring, depending on your needs.
Источник
Запускаем консольные 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.
Источник