Android Gradle 使用Groovy 实现简单的打包上传

背景

Android APP 开发的时候经常给需要测试,经常需要给测试人员安装apk包,如果有一套完整的打包测试流程框架还好,如果没有的话,那就有点麻烦了,经常需要插线安装测试,非常的影响正常的工作,作为一个懒惰的程序员这事不能忍受的,我希望的是我的打测试包的时候自动上传测试包,用户那边能够自动收到包更新信息,自动下载安装

操作

1 groovy 和gradle 基础

groovy 语言和java 语言是兼容的,所以对于我们来说还是很方便的,关于groovy和gradle 重点学习了Groovy脚本基础全攻略和Gradle脚本基础全攻略,这两篇文章,写的很详细,适合入门学习

2 代码

public class UploadPlugin implements Plugin {

    private Project project = null

    @Override
    void apply(Project project) {
        project.extensions.create("debugMessage", Extension)
        this.project = project
        if (project.android.hasProperty("applicationVariants")) {
            project.android.applicationVariants.all { variant ->
                String variantName = variant.name.capitalize()
                Task uoloadTask = createUploadTask(variant)
                uoloadTask.dependsOn project.tasks["assemble${variantName}"]
            }
        }
    }

    private Task createUploadTask(Object variant) {
        String variantName = variant.name.capitalize()
        println("uoload:create uploadTak")
        Task uploadTask = project.tasks.create("upload${variantName}Apk") << {
            uploadApk(variant.outputs[0].outputFile.getAbsolutePath())
        }
        return uploadTask
    }

    private void uploadApk(String path) {
        Map map = new HashMap()
        map.put("file", path)
        postForm(project.debugMessage.url, null, map)
    }


    private String postForm(String urlStr, Map textMap, Map fileMap) throws IOException {
        String res = "";
        HttpURLConnection conn = null;
        InputStream inS = null;
        OutputStream out = null;
        String BOUNDARY = "---------------------------123821742118716";
        //boundary就是request头和上传文件内容的分隔符
        try {
            URL url = new URL(urlStr)
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(19000);
            conn.setReadTimeout(19000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            out = new DataOutputStream(conn.getOutputStream());
            // text value
            if (textMap != null) {
                StringBuffer strBuf = new StringBuffer();
                Iterator iter = textMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String inputName = (String) entry.getKey();
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue
                    }
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
                    strBuf.append(inputValue);
                }
                out.write(strBuf.toString().getBytes());
            }
            // file
            if (fileMap != null) {
                Iterator iter = fileMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String inputName = (String) entry.getKey();
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue
                    }
                    File file = new File(inputValue);
                    println(file.size())
                    String filename = String.format("%s_%s_%s", System.currentTimeMillis(), project.debugMessage.message, file.getName())
                    println(filename)
                    String contentType = ""
                    if (filename.endsWith(".png")) {
                        contentType = "image/png"
                    } else if (filename.endsWith(".gif")) {
                        contentType = "image/gif"
                    } else if (filename.endsWith(".jpg")) {
                        contentType = "image/jpeg"
                    }
                    if (contentType == null || "".equals(contentType)) {
                        contentType = "application/vnd.android.package-archive"
                        //contentType = "application/octet-stream";
                    }
                    StringBuffer strBuf = new StringBuffer()
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n")
                    out.write(strBuf.toString().getBytes())
                    DataInputStream input = new DataInputStream(new FileInputStream(file));
                    int bytes = 0;
                    byte[] bufferOut = new byte[1024];
                    while ((bytes = input.read(bufferOut)) != -1) {
                        out.write(bufferOut, 0, bytes);
                    }
                }
            }

            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData)
            out.flush()

            // 读取返回数据
            StringBuffer strBuf = new StringBuffer();
            inS = conn.getInputStream()
            BufferedReader reader = new BufferedReader(new InputStreamReader(inS));
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line).append("\n")
            }
            res = strBuf.toString()
            println(res)
            reader.close()
            reader = null
        } catch (Exception e) {
            e.printStackTrace();
            println(e.getMessage())
        } finally {
            if (out != null) {
                out.close();
            }
            if (inS != null) {
                inS.close();
            }
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
            println("完成")
        }
        return res;
    }


}

 

总结

buildScript {
     repositories {
         mavenCentral()
}
}

repositories {
     mavenCentral()
}

buildscript中的声明是gradle脚本自身需要使用的资源。可以声明的资源包括依赖项、第三方插件、maven仓库地址等。

而在build.gradle文件中直接声明的依赖项、仓库地址等信息是项目自身需要的资源。

其实这些也是照葫芦画瓢,没有什么好写的,简单记录一下吧

 

参考

https://blog.csdn.net/yanbober/article/details/49047515

https://www.jianshu.com/p/7e8ae21b093a

https://blog.csdn.net/yanbober/article/details/49314255

https://www.flysnow.org/2015/03/30/manage-your-android-project-with-gradle.html

 

你可能感兴趣的:(Android Gradle 使用Groovy 实现简单的打包上传)