我正在尝试使用新的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。

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


当前回答

Android Studio 3+:

你只需要简单地将jar文件复制到app文件夹下的libs文件夹即可。

...myproject \ app \ libs myfile . jar

然后从“项目”窗口的下拉菜单中选择“项目文件”,右键单击该项目,选择“同步”以在“项目文件”中查看该文件。它会自动在gradle文件(Module:app)中添加依赖项。

dependencies {
...
    implementation files('libs/myfile.jar')

这里有另一个解决方案:

转到Project Files视图(从下拉菜单中选择Project Files)。

选择新…在app下面创建一个名为libs的文件夹。

打开文件资源管理器,复制并粘贴jar文件到libs文件夹中。

在Android Studio中,右键单击jar文件,并选择Add as a Library…从弹出式菜单。

你应该在gradle文件的依赖项列表中看到这个文件:

dependencies {
...
    implementation files('libs/myfile.jar')
}

打开你的java文件,在那里添加import语句:

import com.xxx.xxx;

其他回答

下面是将本地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

的编译文件…“以前为我工作,但现在不是了。在经历了很多痛苦之后,我发现用这个方法是有效的:

编译fileTree(dir: 'libs',包括:'*.jar')

我不知道为什么会有不同,但是,至少这该死的东西现在开始工作了。

编译fileTree(dir: 'libs',包括:'*.jar')工作正常,但编译文件(…)已在Studio Beta 0.8.1测试

我已经阅读了这里所有的答案,它们似乎都涵盖了旧版本的Android Studio!

用Android Studio 2.2.3创建一个项目,我只需要在app下创建一个libs目录,并将我的jar放在那里。 我是用我的文件管理器完成的,不需要在Android Studio中点击或编辑任何东西。

为什么有效?打开构建/编辑库和依赖项,你会看到:

{include=[*.jar], dir=libs}

与Eclipse不同,我们不需要下载jar并将其放在/libs文件夹中。Gradle处理这些事情,我们只需要添加Gradle依赖项,Gradle下载并放入Gradle缓存。

我们需要添加依赖项如下:

依赖项{实现'com.google.code.gson:gson:2.2.4'}

这是它 然而,我们也可以下载jar并将其添加为库,但最好的做法是添加Gradle依赖项。