我正在尝试使用新的Android Studio,但我似乎不能让它正常工作。

我正在使用Gson库来序列化/反序列化json对象。但是这个库不知何故没有包含在构建中。

我用MainActivity创建了一个新项目。 复制gson-2.2.3.jar到/libs文件夹中,并将其添加为库依赖项(右键单击->添加为库)。这包括android studio中的jar,因此可以从源文件中引用它。

当我尝试运行项目时,它无法编译,所以我添加:

compile files('libs/gson-2.2.3.jar')

到de .gradle文件中的依赖项。之后,它正确编译,但当运行应用程序时,我得到一个ClassDefNotFoundException。

有人知道我哪里做错了吗?


当前回答

下面是将本地jar文件作为库添加到模块的说明:

Create a 'libs' folder in the top level of the module directory (the same directory that contains the 'src' directory) In the build.gradle file add the following so that your dependencies closure has: dependencies { // ... other dependencies compile files('libs/<your jar's name here>') } Android Studio should have already setup a gradlew wrapper. From the command line, navigate to the top level of your project (the directory that has a gradlew file). Run ./gradlew assemble. This should compile the project with the library. You may need to fix errors in your build.gradle file as necessary. In order to have Android Studio recognize the local jar files as libraries for support while coding in the IDE, you need to take a few more steps: 4.1. Right click on the module in the left hand panel and choose Open Library Settings. 4.2. On the left panel of the dialog, choose Libraries. 4.3. Click the + sign above the panel second from the left -> Java 4.4. Select your local jar and add it to the project. You may need to run the above ./gradlew command one more time

其他回答

在Android Studio 2.1中,我遵循这种方式,

Goto app -> src->主->资产文件夹(如果不可用创建它)->放你的JAR文件

在你的构建中。Gradle像这样添加依赖,

implementation files('src/main/assets/jsoup.jar')
implementation files('src/main/assets/org-apache-xmlrpc.jar')
implementation files('src/main/assets/org.apache.commons.httpclient.jar')
implementation files('src/main/assets/ws-commons-util-1.0.2.jar')

现在同步。 现在您的JAR文件可以使用了。

在project-name/app文件夹中,找到libs文件夹。如果没有libs文件夹,请创建一个。添加.jar文件。右键单击它,您会发现add .jar是一个依赖项。您可以找到添加到构建中的依赖项。gradle文件。

有两种方法可以做到这一点。

第一个简单的方法。

复制.jar文件到剪贴板,然后将其添加到libs文件夹。要查看项目中的libs文件夹,请从文件夹上方的组合框中选择项目。

然后右键单击.jar文件,单击“添加为库”,然后选择一个模块,然后确定。 您可以在构建中看到.jar文件。Gradle文件在依赖块。

 dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation 'com.android.support:appcompat-v7:21.0.3'
        implementation project(':okhttp-2.0.0')
        implementation 'com.google.code.gson:gson:2.3.1'
    }

第二种方法是:我们可以将.jar文件作为.jar模块导入到模块中,然后将该模块添加到我们想要的任何模块中。

导入模块——>选择你的。jar文件——>而不是导入一个。jar文件——

然后按CTRL+ALT+SHIFT+S——> project sturure——>选择你想要添加一个jar的模块——>Dependencendies——> module Dependency。构建。模块的Gradle会自动更新。

在Mac OS X上:

将jar添加为库(将jar拖到libs,右键单击添加为库) 在build.grade中添加compile语句 安装gradle v1.6(使用自制软件) Brew install gradle gradle - v 如果不是v1.6,升级homebrew Gradle清洁(重建android不工作)

这让我理清了思路。

下载并复制你的。jar文件到libs文件夹,然后添加这些行到build.gradle:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.google.code.gson:gson:2.3.1'
}

别忘了按“立即同步”