如何解决Unsupported major.minor version 52.0问题?

 
  

今天运行./gradlew :PandaAndroidDemo:release出现如下错误:

FAILURE: Build failed with an exception.

* Where:
Build file '/Users/shitianci/work/Lab/panda.android/PandaAndroidDemo/build.gradle' line: 1

* What went wrong:
A problem occurred evaluating project ':PandaAndroidDemo'.
> java.lang.UnsupportedClassVersionError: com/android/build/gradle/AppPlugin : Unsupported major.minor version 52.0

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED
 
   

直接点击 run按钮 或者 Build→Generate Build APK 却运行正常。

这里面有两个问题:

  1. 为什么出现Unsupported major.minor version 52.0
  2. 为什么gradle命令和android studio按钮运行结果不一样?

问题一:为什么出现Unsupported major.minor version 52.0

在网上找了一圈,最后在stackoverflow找到了本质原因

You get this error because a Java 7 VM tries to load a class compiled for Java 8

Java 8 has the class file version 52.0 but a Java 7 VM can only load class files up to version 51.0

In your case the Java 7 VM is your gradle build and the class is com.android.build.gradle.AppPlugin

简单来说,就是java的编译环境版本太低,java 8 class file的版本是52,Java 7虚拟机只能支持到51。所以需要升级到java 8 vm才行。

问题二:为什么gradle命令和android studio按钮运行结果不一样?

从问题1来看,肯定Android Studio按钮调用的是java 8 vm,所以查找一下系统配置,最终在Project Structure找到了如下设置:


Paste_Image.png


Android Studio 2.2.2使用了自带的JDK环境,其地址为

/Applications/Android Studio.app/Contents/jre/jdk/Contents/Home

而gradle命令的执行环境是在gradle.properties配置的,其指向为:

org.gradle.java.home=/Library/Java/JavaVirtualMachines/jdk1.7.0_71.jdk/Contents/home

将其修改为:

org.gradle.java.home=/Applications/Android Studio.app/Contents/jre/jdk/Contents/Home

问题解决。

参考:

  1. CircleCI Android Unsupported major.minor version 52.0


作者:沉思的Panda
链接:http://www.jianshu.com/p/5eebd3c609d6
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

你可能感兴趣的:(Java)