Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing the same code across multiple Android Studio projects

I have some code I'd like to use across multiple different projects. Let's say it's some e-commerce code that handles things like payments and shopping carts.

It seems inefficient and dangerous to copy-paste everything across different projects. And if I add one feature or fix one bug in the core e-commerce module, I'd like that change to be reflected in other projects using it too.

I would also like to re-use some of the Activities, Fragments, Adapters too.

What is a good approach to this?

like image 702
Muz Avatar asked Feb 02 '17 07:02

Muz


Video Answer


1 Answers

When we have a library project that needs to be shared to every project on a local computer, we can make use of Maven.

A. Here the step in your library that we will you for the project:

  1. Make a library project from Android Studio.

  2. Add Gradle Android Maven plugin to root build.gradle

    buildscript {
      repositories {
        mavenCentral()
      }
    
      dependencies {
        classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
      }
    }
    
  3. Add apply plugin for step 1 in your library build.gradle. (NOT root build.gradle):

    apply plugin: 'com.android.library'
    apply plugin: 'com.github.dcendents.android-maven'
    
  4. Add the following after the apply plugin, this line to determine your library when adding to project:

    group = 'com.yourpackage.yourlibrary'
    version = '1.0'
    
  5. Add the following code in your settings.gradle:

    rootProject.name = 'yourlibrary' 
    
  6. Then publish it to your local maven with:

    ./gradlew install
    

    Or you can use gradle option in Android Studio.

  7. Your library will be installed in $HOME/.m2/repository. Remember that to use the library you need to add like this:

      Groupid:artifactid:versionid
    

    Artifactid will be package name of your library.

B. Here the step in your Project which using the library:

  1. Add the following code in your root build.gradle:

      mavenLocal() // for local maven.
    

This for getting the local library maven that we have installed in step A

  1. Then in your app project.gradle, add compile for the library:

    compile 'com.yourpackage.yourlibrary:yourlibrary:1.0'
    

Read more:

  • Gradle: How to publish a Android library to local repository
  • https://github.com/dcendents/android-maven-gradle-plugin
  • https://inthecheesefactory.com/blog/how-to-upload-library-to-jcenter-maven-central-as-dependency/en
like image 80
ישו אוהב אותך Avatar answered Sep 28 '22 16:09

ישו אוהב אותך