Running java files 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 recovery

Источник

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

Источник

[Guide] To run .JAR files on Android |Install java apps on Android

nayser

Senior Member

Yes we can install java apps on our android phone & it is possible with the application JBED.

JBED is an .apk Android application which Run
Java Games and Apps on our Android Device.
JBED is a Java Android Java Emulator, by using
this application we can install .JAR/.JAD/Java/
J2ME/MIDP games on Android phones. Now
We can use all of our favorite .JAR
application in our phones.

Steps to Install Jar on Android:

place it in system\lib
folder

3. Install the JBED.apk application and don’t play
it.

4. Restart the phone

5. Launch JBED application. Press menu button
and choose SD card.

6. Select your .JAR/.JAD file that you want to
install and run.

7. Now install the chosen application through
JBED.

6. Now open the installed java application to run.

Thanks to the Brilliant Dev who created the app JBED

vale amicis

Guest

altius_cooper

Senior Member

ZenPluS

Senior Member

vale amicis

Guest

John Chu

Senior Member

Venomous Viper 119

Senior Member

Just wondering . Are you the director of step up movie series, John.M.Chu ?! Lol. Btw, this should working all Android versions.

I had encountered a guy months ago that spoke of running Java apps on android. He talked about having unlimited free internet using Java apps. Is this possible ?! Ain’t no crime ?!

Читайте также:  Simpsons tapped out android пончики

Sent from my GT-S5830 using xda premium

John Chu

Senior Member

Just wondering . Are you the director of step up movie series, John.M.Chu ?! Lol. Btw, this should working all Android versions.

I had encountered a guy months ago that spoke of running Java apps on android. He talked about having unlimited free internet using Java apps. Is this possible ?! Ain’t no crime ?!

Sent from my GT-S5830 using xda premium

Of couse I’m NOT the director. BTW, the correct name is «Jon M. Chu».
It’s possible, based on your ISP.

And the app doesn’t work on my S4.

Venomous Viper 119

Senior Member

Of couse I’m NOT the director. BTW, the correct name is «Jon M. Chu».
It’s possible, based on your ISP.

And the app doesn’t work on my S4.

Yea Will try this

Sent from my Galaxy Ace GT-S5830 using xda premium

Senior Member

the4ndy

Member

I followed your instructions but JBED is not working. After moving the lib and then install and then restart the app installed «Java» with the mug icon, does not run at all, it force closes twice on open.

I have a Nexus 4 running 4.2.2 Jelly Bean.

kayo2013

Member

Hey. it is not working. i can perform each and every step..
But every time , when i open java app..it doesn’t open..and every time it’s force closed.
So now what can i do.

Sent from my GT-S5830 using xda premium

———- Post added at 07:09 AM ———- Previous post was at 07:04 AM ———-

Hey..this is not run in my phone..
I can perform each and every step that you can show. but when i open java app..it can’t run . and every it’s force close.
So what can i do.. .

Sent from my GT-S5830 using xda premium

vvijayraju

New member

not able to copy

Yes we can install java apps on our android phone & it is possible with the application JBED.

JBED is an .apk Android application which Run
Java Games and Apps on our Android Device.
JBED is a Java Android Java Emulator, by using
this application we can install .JAR/.JAD/Java/
J2ME/MIDP games on Android phones. Now
We can use all of our favorite .JAR
application in our phones.

Steps to Install Jar on Android:

place it in system\lib
folder

3. Install the JBED.apk application and don’t play
it.

4. Restart the phone

5. Launch JBED application. Press menu button
and choose SD card.

6. Select your .JAR/.JAD file that you want to
install and run.

7. Now install the chosen application through
JBED.

6. Now open the installed java application to run.

Thanks to the Brilliant Dev who created the app JBED

not able to copy in system\lib what to do.

Shoaib1247

Senior Member

Facing following error.

«Unfortunately java has stopped»

TSpecOne

New member

Facing following error.

«Unfortunately java has stopped»

chinittoh

Senior Member

aerolele

Member

no luck with java on android 4.3 jelly bean

I could not make any java emulator to work on my device Samsung galaxy s4 (i9500). someone had any luck?

atlantis1000

New member

I downloaded both the files and moved
(root file manager) them to
system\lib (cut & paste). But when I searched for
them, they were missing. The only file remotely
related to the original is one called libjavacore.so
which is only 215 kb. The jbed.apk is 3.11 mb. So
my question is: Where the hell have both the files
disappeared? Another thing, is there any way (except
cut n paste) to directly download or move the files to
system\lib?
I am using samsung galaxy grand quattro I8552

Читайте также:  Dust sans fnf android

PatrickFitzmichael

New member

Thanks for this but is there a conspiracy among XDA users to only upload to this crap of a website? I have nothing but problems with this one and seldom is the file there.

pocthird

Senior Member

change permissions to make lib work

works great on galaxy mini 2 with stock 2.3.6 rom , i tried it on a chinease phone with 2.3.7 and it works great i just changed permissions of the xxx.so lib to rw.r.r like the other libs in the lib folder . i hope it works on thewhisp’s cm10.1 rom i’m planing to upgrade . thank you for sharing

Similar threads

Top Liked Posts

Yes we can install java apps on our android phone & it is possible with the application JBED.

JBED is an .apk Android application which Run
Java Games and Apps on our Android Device.
JBED is a Java Android Java Emulator, by using
this application we can install .JAR/.JAD/Java/
J2ME/MIDP games on Android phones. Now
We can use all of our favorite .JAR
application in our phones.

Steps to Install Jar on Android:

place it in system\lib
folder

3. Install the JBED.apk application and don’t play
it.

4. Restart the phone

5. Launch JBED application. Press menu button
and choose SD card.

6. Select your .JAR/.JAD file that you want to
install and run.

7. Now install the chosen application through
JBED.

6. Now open the installed java application to run.

Thanks to the Brilliant Dev who created the app JBED

Not enough space in system/bin

I cannot copy the libjbedvm.so file in my system/bin folder. It is showing 2.16mb free space and the libjbedvm.so file is of 3.11mb. Is there a way to get more free space,if so please reply. Any help would be appreciated and thanks.
Sorry for bad english.

Flashable zip version

Found another thread like this one that has a flashable zip version to copy the lib and set the permissions corectly
http://forum.xda-developers.com/showthread.php?t=1189303

haven’t tried it myself as I’ve JDK softfloat running on all my devices with a different method entirely but thought it would help as the last four pages have mainly had to do with setting permissions or not copying corectly. Furthermore there be a short video on Youtube
https://www.youtube.com/watch?v=eoj4Tiah6PE

which dimenstrates all the required tasks. @nayser; I would suggest adding those links to your OP so future readers may benofit from having a flashable zip; some devices have «sOff» vs «sOn» security that prevents writing or setting permissions wile the Android OS is fully booted (myTouch 3Gs from HTC for example).

To those that are wondering about running JDK (Java’s Development tool Kit) which comes with a full java virtual machien, run time enviroment, and for hard float and some processors of soft float a full server; it’s a bit more work than installing an app and lib but posible for gingerbread on up if you’re willing to run Linux in chroot or with Debian Kit app (which I preffer because of the long list of devices it works on) and run a few scripts to download and install into that Linux enviroment from github
https://github.com/S0AndS0/Debian-Kit-Mods

just be sure to set a normal user with sudo permissions and choose the corect «flavor» of Java (if your Linux OS is hardfloat then choose the hardfloat JDK and the same for softfloat) and before atempting reolize that this isn’t for j2me mobile java but for any java or jar file that runs on Linux without cpu restrictions.

Источник

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