Monday, September 21, 2015

How to create and use a Jar archive using Android Studio

I wanted to consolidate some Java classes into a common library so that it can be shared among Android projects. A Java archive file (*.jar) is a typical container for this purpose. Android Studio can generate and use a Java archive (Jar) file containing commonly used classes and resources. But since we are using Android Studio, an Android project must be created first, then a Jar module can then be created and added. The following steps illustrate the process in creating a Jar file.

Generating a Java archive (*.jar) file

  1. Start up Android Studio.

  2.  Select Start a new Android Studio project.

    The Create New Project dialog box appears.

  3. Type in an Application name and a Company Domain. Select a Project location. Click Next.

    The Target Android Devices page appears.

  4.  Choose a Minimum SDK, e.g. API 14. Click Next.

    The Add an activity to Mobile page appears.

  5. Select Add No Activity. Click Finish.

    The Android project is created.
  6. Select File | New | New Module.

    The Create New Module dialog box appears.

  7. Select Java library.

    The Customize the Activity page appears.

  8. In the Library name field, type in the name of the library e.g. libDijkstra. In the Java class name field, type in the name of the class e.g. MyClass. Press Enter.

    The library is created.
  9. Type in the classes and methods of the library in the editor e.g. printHello method in the file.
  10. In the Project tree view, select the newly created module node, e.g. libdijkstra. Then open the Gradle projects pane on the right side. Expand the Tasks node, as shown below.

  11. Double click on build.

    The Java archive file is generated, e.g. libdijkstra.jar.

Using the Java archive (*.jar) file
  1. In Android Studio, create a new project or open up an existing project e.g. MyApplication that you want to use the Java archive file library.
  2. In the Project view, expand the libs node of your app, as shown below.

  3. Using the Windows Explorer, select and copy the Java archive file (*.jar) e.g. libdijkstra.jar. In Android Studio, right click on the libs folder of the app. Paste the Jar file.

    The Copy dialog box appears.

  4. If necessary, change the name. Click OK.

    The Jar file is added to the project.
  5. Select File | Project Structure.

    The Project Structure dialog box appears.

  6. Select app. On the right side, click the plus +.

    The Select Path dialog box appears.

  7. Browse and select the Java archive file e.g. libdijkstra.jar. Click OK.

    Now the classes and methods in the Java archive file can be used in your app, as shown in the example below.


Alin said...

Thanks, this helped me a lot!

Unknown said...

how can i use to archive all classes and resurces

jatin bansal said...

libs folder not create inside build folder and dont know where is jar saved

Related Posts with Thumbnails