Thursday, March 30, 2017

Build jar file using java sdk 1.7 on mac for android studio library

Currently by default, java SDK 1.8 will be installed on mac for compile java code. However, a jar file compiled using java sdk 1.8 cannot be used by Android studio (2.3) as library project. The android project will build without error, but it will fail when trying to debug the app on device or simulator. Set SourceCompatiblity Setting in app's build.grade file also does not help.

One way to solve the issue is building the jar file with java sdk 1.7.

To do so, first download Java SE sdk 1.7 from oracle web site, and then install it on your mac. You do not need to first uninstall Java 1.8 from your mac, the new java 1.7 will be installed on the mac, but it will not remove or change any settings used by the current installed java sdk 1.8.

After the installation is done, you can check there should have two sub folders under
/Library/Java/JavaVirtualMachines   
One for 1.8 and one for 1.7.

Now you need a way to switch the java sdk version from terminal app to build the java source code. The easy way to do so is add the below two lines in your .bash_profile
alias setJdk7='export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)'
alias setJdk8='export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)'

After saving the change in bash_profile, then you can switch the java sdk version by typing the below command from terminal app:

setJdk7
set java sdk to 1.7

sdkJdk8
set java sdk to 1.8

With the above change, you can rebuild the jar file using jdk 1.7 and then import the jar file into the android studio, it should be able to build and run on device and simulator without problem.

Note: when adding new jar file as a module in android studio project, the settings.gradle will be updated to include the jar file. you will need manually add the new module in app's build.gradle's dependency section.

No comments:

Post a Comment