Search code examples
androidandroid-studioandroid-studio-2.1

Android Studio: Using Common Java Classes


This is insane to me, I've been searching all night, but can't figure out how to do this.

I have the following directory structure:

|
|Android Project1
|  (app, build, lib, etc)
|
|Android Project2
|  (app, build, lib, etc)
|
|Common Classes
|  (Constants.java, Config.java)

In Android Project1 and Android Project2, I would like to use the Constant.java class that has definitions for a lot of things that both Android Project1 and Android Project2 have.

How, do I use those java classes in either of those Android Projects? It's like if stuff isn't inside of the Android Project itself, it's a huge pain in the ass to get Android Studio to see/use/import/whatever I need. I've been Googling for hours, and haven't found a perfect, elegant solution.

In my specific implementation, the common classes contain a TCP client library, and custom class for my project; both pure Java. I have a tiny test application, and a very large production application, both of which use the common classes. I want to keep the pure Java common stuff separate from each project's Android stuff.

Thank you.


Solution

  • You can put Common Classes as a library project. To make a new libraray project, in AS: Choose File > New > New Module and select Android Library. To change an existing application to library change in your build.gradle file

    apply plugin: 'com.android.applicaion'
    

    to

    apply plugin: 'com.android.library'
    

    To use this library in another project you can:

    1 - Click File > New Module.
    2 - Click Import .JAR/.AAR Package then click Next.
    3 - Enter the location of the AAR or JAR file then click Finish.
    

    Or, Import the library module to your project:

    Click File > New > Import Module.
    Enter the location of the library module directory then click Finish.
    

    Hope this solves your issue.