Setup Gradle to run Java executable in Android Stu

2019-02-12 16:02发布

问题:

So here's the deal: I'm using ORMLite for Android, which uses annotations for it's mapping in Android. As you know, annotations are slow in Android, and the makers of ORMLite have realized this, so they added the ability to run a java executable to generate a resource file that bypasses the need to check annotations at runtime in the android app. It looks something like this:

public class DatabaseConfigUtil extends OrmLiteConfigUtil {
  private static final Class<?>[] classes = new Class[] {
    SimpleData.class,
  };
  public static void main(String[] args) throws Exception {
    writeConfigFile("ormlite_config.txt", classes);
  }
}

I need a way to run this java executable every once in a while. To sum this up: I need a way to run a java executable in Android Studio. It can be via Gradle, another run configuration, part of a JUnit test, I don't really care. I just need the ability to run this from AndroidStudio.

This is my current Gradle Script:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.5.+'
    }
}
apply plugin: 'android'

repositories {
    mavenCentral()
}

android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 18
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
    compile project(':AndroidLibrary')

    compile 'com.j256.ormlite:ormlite-android:4.47'
}

回答1:

I use IDE configuration for this. Here is how to achieve it:

  1. in menu select Run -> Edit configuration
  2. press plus icon -> Application
  3. Name: OrmLite DB config, Main class: com.yourclasspath.DatabaseConfigUtil, Use classpath of module: main
  4. switch to your main build configuration and in the Before launch press plus icon -> Run another configuration and select OrmLite DB config

Now everytime you build your main configuration it also executes DatabaseConfigUtil.

If you dont want to run DatabaseConfigUtil before every build just skip step 4 and run it from configuration selection next to the Run icon in the toolbar.