- Java run class java file on android
- How can I run a java.class from Main Activity
- Run a Java application in Android Studio
- How to Run Pure / Standard Java Program in Android Studio
- How to Run Java Program in Android Phone
- Android compile single .java file to .class
- Dynamically compile .java file into .class
- How to call java classes of a compiled jar file within android studio?
- How to Run Java Code in Android Studio
- How to run Java programs 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?!
- Follow up articles
Java run class java file on android
also,android has no JDK it has DVM(Dalvik Virtual Machine) or ART(Android Runtime) which is responsible to convert .dex file to machine dependent code. Solution 1: Compiling a java file in a mobile/android device is not possible because Mobile device don’t have a JDK for converting .java file to .class file.
How can I run a java.class from Main Activity
public class MainActivity extends AppCompatActivity < private static final InetSocketAddress local = new InetSocketAddress("192.168.10.13", 3671); private static final InetSocketAddress server = new InetSocketAddress("myKnxServer.myHome", KNXnetIPConnection.DEFAULT_PORT); @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // call your method to do the task yourMethodForMakingConnection(); >// for better separation you can create a method for this task private void yourMethodForMakingConnection() < System.out.println("This example establishes a tunneling connection to the KNXnet/IP server " + server); // A KNX tunneling link supports NAT (Network Address Translation) if required. // We also indicate that the KNX installation uses twisted-pair (TP) medium, with TP1 being the most common. // KNXNetworkLink is the base interface implemented by all supported Calimero links to a KNX network. try (KNXNetworkLink knxLink = KNXNetworkLinkIP.newTunnelingLink(local, server, false, TPSettings.TP1)) < System.out.println("Connection established to server " + knxLink.getName()); System.out.println("Close connection again"); >catch (KNXException | InterruptedException e) < // KNXException: all Calimero-specific checked exceptions are subtypes of KNXException // InterruptedException: longer tasks that might block are interruptible, e.g., connection procedures. In // such case, an instance of InterruptedException is thrown. // If a task got interrupted, Calimero will clean up its internal state and resources accordingly. // Any deviation of such behavior, e.g., where not feasible, is documented in the Calimero API. System.out.println("Error creating KNXnet/IP tunneling link: " + e); >> >
This should work if the code is correct. Think of the onCreate function of your Activities as the main function. You don’t need another class for a task that small.
Or else, you can otherwise also just create an instance of that class inside your onCreate method in the MainActivity and just call the main method that establishes the connection from that class with the object.
Either way, you’ll be able to do it.
You can learn more about the basics of Android Development, Activity, and Android Activity lifecycle so that you can understand this better.
How to Execute a .class File in Java?, To compile your .java files, open Terminal (Mac) or Command Prompt (Windows). ; 2. Navigate to the folder your java file is at. ; 3. To compile
Run a Java application in Android Studio
Step by step guide to run Java in Android Studio although there are better IDEs that can do Duration: 9:23
How to Run Pure / Standard Java Program in Android Studio
In this video you will learn how to run java project in android studio.This video demonstrates
Duration: 7:34
How to Run Java Program in Android Phone
Android compile single .java file to .class
These error messages are the java compiler telling you that there’s some android dependencies that he can’t figure out how or where to find.
I don’t think it’s possible to achieve this, because it seems your class relies on Android framework resources.
Take a look at: compile android app with javac
Did you consider inheritance ? I mean, the desired different behaviour for android maybe can be achieved by inheriting the class then overriding the specific method with new behaviour, I’m just guessing, since I don’t have enough info about your problem.
Run a Java application in Android Studio, Step by step guide to run Java in Android Studio although there are better IDEs that can do Duration: 9:23
Dynamically compile .java file into .class
Compiling a java file in a mobile/android device is not possible because Mobile device don’t have a JDK for converting .java file to .class file.
also,android has no JDK it has DVM(Dalvik Virtual Machine) or ART(Android Runtime) which is responsible to convert .dex file to machine dependent code.
To achieve this you have to implement a JDK in your application and since JDK/JVM is platform dependent your have to write your own code for JDK to work in your application.
I want to suggest you to take a look at JRE (Java Runtime environment) and JDK (Java Development Kit).
I use groovy . Learn more details. You can run dynamically.
import groovy.lang.GroovyShell; import groovy.lang.Script; public class Test < public static void main(String[] args) throws Exception< String input = "public int calculate() < " + " return 5 + 10;" + ">"; Script groovyShell = new GroovyShell().parse(input); int result = (Integer)groovyShell.invokeMethod("calculate", null); System.out.println("Result : " + result); > >
Here is example dynamic input from my web application. The user input this script/java code from UI. We was have calculation which was change frequently. That’s why we was think dynamic calculation way.
My program is run dynamically
The following script/java code come form UI input..
import java.math.BigDecimal; import java.math.RoundingMode; import java.util.HashMap; import java.util.Map; import com.java.groovy.DateUtils; import com.java.groovy.ParamConstant; import com.java.groovy.CalcConstant; import com.java.groovy.CalcResult; public Map calculate(Map map) < def script = new GroovyScriptEngine('resources/').with ; this.metaClass.mixin script; BigDecimal oldPremium = map.get(ParamConstant.OLD_PREMIUM); Date startDate = map.get(ParamConstant.START_DATE); Date endDate = map.get(ParamConstant.END_DATE); Date endorsementDate = map.get(ParamConstant.ENDORSEMENT_DATE); BigDecimal actRate = map.get(ParamConstant.ACTUAL_RATE); int year = DateUtils.getPeriodOfYears(startDate, endDate); int term = 0; if (year >= 1) < term = DateUtils.getPeriodOfDays(startDate, endDate); >else < term = DateUtils.getPeriodOfDays(startDate, endDate) + 1; >int passedDays = DateUtils.getPeriodOfDays(startDate, endorsementDate) + 1; int restDays = DateUtils.getPeriodOfDays(endorsementDate, endDate) + 1; Map result = new HashMap(); // Calculate Short Period Rate BigDecimal shortPeriodRate = new BigDecimal(calcMotorShortPeriodRate(startDate, endDate)); BigDecimal newPremium = actRate.multiply(shortPeriodRate); // Pro-Rata Rate with old vehicle BigDecimal oldVehProRataRate = calcMotorProRataRate(passedDays, oldPremium.doubleValue(), term); // Pro-Rata Rate with new vehicle BigDecimal newVehProRataRate = calcMotorProRataRate(restDays, newPremium.doubleValue(), term); BigDecimal balanceAmountWithOldPremium = (oldPremium.subtract(oldVehProRataRate)); BigDecimal endorseAmount = (newVehProRataRate.subtract(balanceAmountWithOldPremium)); newPremium = newPremium.setScale(CalcConstant.RESULT_DECIMAL_LIMIT, RoundingMode.HALF_UP); result.put(CalcResult.PREMIUM, newPremium); endorseAmount = endorseAmount.setScale(CalcConstant.RESULT_DECIMAL_LIMIT, RoundingMode.HALF_UP); result.put(CalcResult.ENDORSEMENT_AMOUNT, endorseAmount); return result; >
How can I run a java.class from Main Activity, Or else, you can otherwise also just create an instance of that class inside your onCreate method in the MainActivity and just call the main
How to call java classes of a compiled jar file within android studio?
I’m going to assume you’ve already written your import statement for the jar class. If you already put the jar file in the /lib folder, Android Studio should update your build.gradle file. Check to see if you have a link to the jar file in your dependencies <. >If not, you can add it manually.
Just like in normal java you have to add an import to the correct package at the top of your file for everything that’s not in the same package the file is in.
It should look something like this:
but instead of android.view.view it would be a reference to the class in the jar you’re trying to add
How to Run Java Program in Android Phone, How to write a Java Program in Android Mobile and Smartphone? Write a program of Java Duration: 5:43
How to Run Java Code in Android Studio
Along with Kotlin Android SDK runs with Java programming language. Whereas if you specifically need to run the java code in Android Studio, it is difficult to run without accessing any of Android building blocks like Activity or Services or Broadcast Receivers. However, you can run Java code within Android Studio by creating a separate module. So let’s learn how to run Java code in Android Studio.
Initially, we assume that you have already created an Android project with Android Studio IDE.
1. Create a new module by going to File –> New and hit on the New Module.
2. After hitting New Module, select Java Library and name it on the next screen. Further, finish it.
After creating a Java Library module it will be displayed in the Android Studio.
3. In the third step, you need to configure Android Studio to Run the Java module(created in the previous step). Hit on Edit Configurations… from the drop-down.
In the Run/Debug Configurations window, hit on the ‘+’ button from the top left corner. Later select Application from the drop-down and name it as ‘Java’.
4. While in the same Run/Debug Configurations window, provide the main class field with the class name along with the package name of the Java module.
Finally, you have created a Java module to run Java code and configured it. Afterward, we create a sample code in the MyClass and run it.
MyClass.java
package com.shadow.technos.javacodelib; public class MyClass < private static final String TAG = MyClass.class.getSimpleName(); public static void main(String[] args)< System.out.println("running "+TAG+" java code"); >>
Select java configuration and run it. Later Check Run tab in Android Studio to check the output of the code.
How to run Java programs directly on Android (without creating an APK)
A step by step instruction for compiling a Java program into an 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:
package com.example; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; public class HelloWorld public static void main(String[] args) throws ParseException Option version = new Option("v", "Print version"); Option help = new Option("h", "Print help"); Options options = new Options(); options.addOption(help); options.addOption(version); for (Option opt : new DefaultParser().parse(options, args).getOptions()) if (opt.equals(version)) String os = System.getProperty("os.arch"); System.out.println("Hello World (" + os + ") v0.1"); > if (opt.equals(help)) new HelpFormatter().printHelp("Hello World", options); > > > >
Setting up the working directory
We will have to manually run several commandline tools in the next step, assuming the following final directory structure:
. ├── android-sdk-linux │ └── build-tools │ └── 23.0.2 │ └── dx ├── bin │ └── com │ └── example │ └── HelloWorld.class ├── lib │ └── commons-cli-1.3.1.jar ├── src │ └── com │ └── example │ └── HelloWorld.java ├── helloworld.jar └── helloworld.sh
- 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:
javac -source 1.7 -target 1.7 -d bin -cp lib/commons-cli-1.3.1.jar src/com/example/HelloWorld.java
Make sure the program compiled properly:
java -cp lib/commons-cli-1.3.1.jar:bin com.example.HelloWorld -h usage: Hello world -h Print help -v Print version
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):
./android-sdk-linux/build-tools/23.0.2/dx --output=helloworld.jar --dex ./bin lib/commons-cli-1.3.1.jar
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.
base=/data/local/tmp/helloworld export CLASSPATH=$base/helloworld.jar export ANDROID_DATA=$base mkdir -p $base/dalvik-cache exec app_process $base com.example.HelloWorld "$@"
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:
adb shell mkdir -p /data/local/tmp/helloworld adb push helloworld.jar /data/local/tmp/helloworld adb push helloworld.sh /data/local/tmp/helloworld adb shell chmod 777 /data/local/tmp/helloworld/helloworld.sh
Moment of truth (fingers crossed):
adb shell /data/local/tmp/helloworld/helloworld.sh -v Hello World (armv7l) v0.1
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.