How to generate apk file programmatically through java code

后端 未结 4 1151
孤城傲影
孤城傲影 2020-12-14 05:06

I need to generate or build an APK file through some Java program where I select the Android source project. Suppose I have a button on a web page. When clicked, it generate

相关标签:
4条回答
  • 2020-12-14 05:36

    You can use the ANT jars ant.jar and ant-launcher.jar.
    In this case the path for build.xml should be fully specified. Call it from your Java class this way:

    public class AntTest {
    public static void main(String[] args) {
        String build = "D:/xampp/htdocs/aud/TempProject/build.xml";
        generateApkThroughAnt(build);
    }
    /*
     * Generate APK through ANT API Method
     */
    public static void generateApkThroughAnt(String buildPath) {
        File antBuildFile = new File(buildPath);
        Project p = new Project();
        p.setUserProperty("ant.file", antBuildFile.getAbsolutePath());
        DefaultLogger consoleLogger = new DefaultLogger();
        consoleLogger.setErrorPrintStream(System.err);
        consoleLogger.setOutputPrintStream(System.out);
        consoleLogger.setMessageOutputLevel(Project.MSG_INFO);
        p.addBuildListener(consoleLogger);
        BuildException ex = null;
        try {
            p.fireBuildStarted();
            p.init();
            ProjectHelper helper = ProjectHelper.getProjectHelper();
            p.addReference("ant.projectHelper", helper);
            helper.parse(p, antBuildFile);
            p.executeTarget("clean");
            p.executeTarget("release");
        } catch (BuildException e) {
            ex = e;
        } finally {
            p.fireBuildFinished(ex);
        }
       }
       }
    

    To create a build.xml file go to Eclipse=>Your Project=>Right click=>Export=>General=>Ant Buildfiles. After that then you will need to run:

    android update project --name <project_name> --target <target_ID> --path <path_to_your_project>
    
    0 讨论(0)
  • 2020-12-14 05:39

    Check out this question and replace the cmd commands in the example with your build commands.

    0 讨论(0)
  • 2020-12-14 05:43

    I think you answer yourself to your question : use Runtime.getRuntime() and build the apk using ant or gradle.

    0 讨论(0)
  • 2020-12-14 05:49

    An apk file is basically zip file. It's contains your resources and class dex files. Zygote create dalvik process, dalvikvm execute your java codes. You cannot create apk file programaticcally because it's look like classdex+resourcesmap. If you create programmatically apk write some ascii chars in text file wher is your drawable? Where is your app icon? But you will execute java class use dalvikvm. (Basiccally run class command -c ...)

    0 讨论(0)
提交回复
热议问题