Reusing the same code across multiple Android Studio projects

大兔子大兔子 提交于 2019-12-13 13:49:17

问题


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?


回答1:


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



回答2:


From my Knowledge 1. As others said try creating your own Module or Library and use it where ever you need 2.Use Version Control Tools Like Git(If your code changes it will be refleted in your git account)



来源:https://stackoverflow.com/questions/41996353/reusing-the-same-code-across-multiple-android-studio-projects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!