Acerca del desarrollo de Android grovvy (1) informe automático de confusión de errores

fondo

Empaquetar, mapear y cargar todos los problemas se desarrollan mucho. ¿Tiene dificultades para copiar y pegar? De todos modos lo soy. Entonces, hay esto

efecto final

Por favor agregue la descripción de la imagen.
El efecto final es hacer clic en el paquete gradle del proyecto, copiar el archivo de mapeo e informar automáticamente la confusión de errores.

ambiente

win10
gradle7.5
jdk8,jdk11
as2022+

Nota especial

jdk requiere jdk8 y jdk11. Porque el paquete jar informado por bugly solo se puede ejecutar con jdk8.
Insertar descripción de la imagen aquí
La imagen de arriba es la descripción oficial de la carga de la tabla de símbolos con errores. No se ha actualizado durante dos años. Es posible que haya sido estable. De todos modos, solo puedes usar jdk8.
Para aquellos que no saben cómo cargar tablas de símbolos, pueden leer este artículo.
https://blog.csdn.net/motosheep/article/details/130398365

Empezar a codificar

En primer lugar, escribir un script similar a grovvy requiere una cierta base de Java. No entraré en demasiados detalles aquí, haga su propia investigación.
Esto se divide principalmente en dos partes principales:
(1) Copiar el archivo de mapeo
(2) Cargar el archivo de mapeo


¡Comience! ! Debido a que es demasiado simple, hablaremos juntos de dos pasos.
Copiar archivos, ir y venir, es una operación de flujo y, en grovvy, ¡solo necesita usar Files.copy para completar la operación! ¡Es conveniente!
Ahora que el código principal está terminado, puede cerrar la página web. Por favor agregue la descripción de la imagen.
Bueno, volvamos al asunto.
Primero, el proceso general es el siguiente:
busque el directorio de mapeo generado por el paquete de lanzamiento -> copie el archivo de mapeo a un directorio personalizado -> cargue el archivo de mapeo en bugly. Para cargar, escribí un script bat aquí, ¡al que se puede llamar directamente en el código!

! ! ! ¡Aviso! ! !
El archivo xxx.gradle que usted mismo escribió debe colocarse en el directorio raíz del proyecto. Luego, debe usar las instrucciones en el archivo build.gradle en el proyecto de la aplicación: aplicar desde: ".../copyFileBat.gradle" para presentarlo y luego escribir felizmente la tarea.

Cabe señalar aquí que copiamos y cargamos solo después de ejecutar ensamblarRelease. Hay todo tipo de códigos a través de Baidu. Finalmente, después de constantes intentos, finalmente lo logré. El código se publica a continuación con un solo propósito: ¡evitar que las generaciones futuras se desvíen!

/**
 * 在打完正式包后执行(assembleRelease)
 */
project.tasks.whenTaskAdded { Task task ->
    if (task.name == 'assembleRelease') {
        task.doLast {
           //todo 操作
        }
    }
}

Nuestras copias y cargas están codificadas en el alcance de todo.
Para copiar, simplemente pase las rutas completas de los dos archivos y realice una llamada API. Por ejemplo:
a.jpg, b.jpg
Files.copy(new File(a.jpg).toPath(), new File(b.jpg).toPath()) ¡
puede realizar la copia!

En el proyecto, la ruta de mapeo general es la siguiente:

Insertar descripción de la imagen aquí
Bien, ahora que tiene la ruta del archivo fuente y las instrucciones de copia, creemos un directorio y juguemos. – Son solo algunas operaciones de la API de archivos, pero recuerde crear el directorio principal antes de copiar, para que no se informen errores de IO.

Todo el código principal se publica a continuación:

archivo copyFileBat.gradle:

import java.nio.file.Files
import java.text.SimpleDateFormat

ext {
    //copyFile
    def CopyFilePath = "${rootProject.rootDir}/copytask/"

    //mapping文件原始目录
    MappingFileOrgPath = "${project.buildDir}/outputs/mapping/release/mapping.txt"
    //mapping复制文件目标目录
    def mappingRadonFile = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "mapping.txt"
    MappingFileRootPath = CopyFilePath + "/mapping/"
    MappingPathName = MappingFileRootPath + mappingRadonFile

    //源apk文件
    ApkSourcePath = "${project.buildDir}/outputs/apk/release/"
    //复制apk目标文件夹
    ApkTargetPath = CopyFilePath + "/release/"

    //!!!!!!!!!!bugly 混淆上传相关,需要按照项目配置!!!!!!!!!!!!!!
    //jdk8运行环境
//    JDK8Path = "D:\\software\\java\\jdk1.8\\bin\\java.exe"
    JDK8Path = "D:\\software\\Java\\jdk1.8.0_211\\bin\\java.exe"
    BuglySymJar = new File("${rootProject.rootDir}").parent + "/buglyqq-upload-symbol/buglyqq-upload-symbol.jar"
    BuglySymMappingPath = new File("${rootProject.rootDir}").parent + "/buglyqq-upload-symbol/mappingfile"
    BuglyPackageName = "com.example.androidjiaguchannel"
    BuglyKey = "d89bcdce-978b-4485-8ff4-a95b20372ed6"
    BuglyId = "877be21cd4"
    BuglyBat = new File("${rootProject.rootDir}").parent + "/buglyqq-upload-symbol/run.bat"
}

/**
 * 查找apk文件
 * @param path
 * @param suffix
 * @return
 */
private static File findApkFile(path, suffix) {
    def dir = new File(path)
    return dir.listFiles().find { it.isFile() && it =~ /.*${suffix}\.apk/ }
}

/**
 * 查找txt文件
 * @param path
 * @param suffix
 * @return
 */
private static File findTxtFile(path, suffix) {
    def dir = new File(path)
    return dir.listFiles().find { it.isFile() && it =~ /.*${suffix}\.txt/ }
}

/**
 * 复制mapping文件
 * */
private static boolean copyMapping(MappingFileOrgPath, MappingFileRootPath, MappingPathName) {
    //复制mapping文件
    System.println("----------------assembleRelease finish----------------")
    try {
        System.println("----------------copy mapping file start---------------")
        def orgMappingFilePath = new File(MappingFileOrgPath)
        def targetMappingPath = new File(MappingFileRootPath)
        targetMappingPath.deleteDir()
        targetMappingPath.mkdirs()
        def targetMappingFilePath = new File(MappingPathName)
        Files.copy(orgMappingFilePath.toPath(), targetMappingFilePath.toPath())
        System.println("----------------copy mapping 目录---------------")
        System.println(targetMappingFilePath.toPath())
    } catch (Exception e) {
        e.printStackTrace()
        System.println("----------------copy mapping error,不再进行后续操作----------------")
        return false
    }
    return true
}

/**
 * 复制apk文件
 * */
private static boolean copyReleaseApk(ApkSourcePath, ApkTargetPath) {
    //复制生成的apk release文件
    try {
        System.println("----------------copy release apk---------------")
        System.println("----------------copy apk file start---------------")
        def findSourceApk = findApkFile(ApkSourcePath, "-release")
        if (findSourceApk == null) {
            System.println("----------------copy apk can‘t find-------------")
            return
        }
        def sourceApkNameFullPath = findSourceApk.toPath().toString()
        def fileNameStartPos = sourceApkNameFullPath.lastIndexOf(File.separator)
        def sourceFileName = "app-release.apk"
        if (fileNameStartPos != -1) {
            sourceFileName = sourceApkNameFullPath.substring(fileNameStartPos + 1)
        }
        def orgApkFilePath = findSourceApk
        def targetApkPath = new File(ApkTargetPath)
        targetApkPath.deleteDir()
        targetApkPath.mkdirs()
        def targetApkFilePath = new File(ApkTargetPath + sourceFileName)
        Files.copy(orgApkFilePath.toPath(), targetApkFilePath.toPath())
        System.println("----------------copy apk 目录---------------")
        System.println(targetApkFilePath.toPath())
    } catch (Exception e) {
        e.printStackTrace()
        System.println("----------------copy apk error,不再进行后续操作----------------")
        return false
    }
    return true
}

/**
 * bugly mapping上传
 * */
private static void buglyMappingUpload(JDK8Path, BuglyBat, BuglySymMappingPath, MappingFileRootPath,
                                       BuglySymJar, BuglyPackageName, BuglyId, BuglyKey) {
    try {
//复制mapping文件到脚本目录,然后上传到bugly
        def jdk8File = new File(JDK8Path)
        if (!jdk8File.exists()) {
            System.println("----------------mapping上传要求的jdk8环境不存在---------------" + jdk8File.toPath())
            return
        }
        def outsidePath = BuglyBat
        def uploadBatFile = new File(outsidePath)
        if (!uploadBatFile.exists()) {
            System.println("----------------mapping上传脚本不存在---------------")
            return
        }
        def outsideMappingPath = BuglySymMappingPath + "/"
        new File(outsideMappingPath).mkdirs()
        System.println("----------------mapping上传脚本开始---------------")
        def findSourceMappingFile = findTxtFile(MappingFileRootPath, "mapping")
        if (findSourceMappingFile == null) {
            System.println("----------mapping上传错误,源文件不存在----------")
            return
        }
        def orgFileName = "mapping.txt"
        def fileNameStartPos = findSourceMappingFile.toPath().toString().lastIndexOf(File.separator)
        if (fileNameStartPos != -1) {
            orgFileName = findSourceMappingFile.toPath().toString().substring(fileNameStartPos + 1)
        }
        //外部mapping文件
        def outSizeFilePath = outsideMappingPath + orgFileName
        def outsideFile = new File(outSizeFilePath)
        outsideFile.delete()
        Files.copy(findSourceMappingFile.toPath(), outsideFile.toPath())
        System.println("bugly文件路径: " + outsideFile.toPath())
        System.println("脚本路径:" + uploadBatFile.path)
        Process process = Runtime.getRuntime().exec("cmd /c start " + uploadBatFile.path +
                " ${JDK8Path} ${BuglySymJar} " +
                "${BuglyPackageName} ${BuglySymMappingPath} ${outSizeFilePath} ${BuglyId} ${BuglyKey}")
        process.waitFor() // 等待批处理文件执行完成
        int exitCode = process.exitValue() // 获取批处理文件的退出码
        System.out.println("批处理文件执行完成,退出码:" + exitCode)
    } catch (Exception e) {
        e.printStackTrace()
        System.println("mapping上传错误:\n" + e.printStackTrace())
    }
}


/**
 * 在打完正式包后执行(assembleRelease)
 */
project.tasks.whenTaskAdded { Task task ->
    if (task.name == 'assembleRelease') {
        task.doLast {
            //源mapping复制
            if (!copyMapping(MappingFileOrgPath, MappingFileRootPath, MappingPathName)) {
                return
            }
            //源apk复制
            if (!copyReleaseApk(ApkSourcePath, ApkTargetPath)) {
                return
            }
            //bugly mapping 上传
            buglyMappingUpload(JDK8Path, BuglyBat, BuglySymMappingPath, MappingFileRootPath,
                    BuglySymJar, BuglyPackageName, BuglyId, BuglyKey)
        }
    }
}



script bat para cargar archivos:

@echo off
CLS
chcp 65001
echo 参数jdk8路径:%1
echo 参数bugly混淆jar路径:%2
echo 参数bugly目标包名:%3
echo 参数bugly混淆文件父目录:%4
echo 参数bugly混淆文件全路径:%5
echo 参数bugly Id:%6
echo 参数bugly Key:%7
echo "------------------------java版本信息------------------------"
%1 -version
echo "------------------------begin------------------------"
echo "------------------------注意!注意!注意!mapping文件需要放在mappingfile目录下------------------------"
echo "------------------------版本号------------------------"
set /p codeInput="请输入app版本号(例如:1.0.0):"
echo 输入app版本号为:%codeInput%

echo "------------------------开始上传------------------------"
%1 -jar %2 -appid %6 -appkey %7 -bundleid %3 -version %codeInput% -platform Android -inputSymbol %4 -inputMapping %5
pause

¡Aviso! ! !

En el archivo copyFileBat.gradle:

    //!!!!!!!!!!bugly 混淆上传相关,需要按照项目配置!!!!!!!!!!!!!!
    //jdk8运行环境
//    JDK8Path = "D:\\software\\java\\jdk1.8\\bin\\java.exe"
    JDK8Path = "D:\\software\\Java\\jdk1.8.0_211\\bin\\java.exe"
    BuglySymJar = new File("${rootProject.rootDir}").parent + "/buglyqq-upload-symbol/buglyqq-upload-symbol.jar"
    BuglySymMappingPath = new File("${rootProject.rootDir}").parent + "/buglyqq-upload-symbol/mappingfile"
    BuglyPackageName = "com.example.androidjiaguchannel"
    BuglyKey = "d89bcdce-978b-4485-8ff4-a95b20372ed6"
    BuglyId = "877be21cd4"
    BuglyBat = new File("${rootProject.rootDir}").parent + "/buglyqq-upload-symbol/run.bat"

Debe modificarse según la información de configuración de su computadora y proyecto. Todas las variables involucradas anteriormente deben redefinirse: ¡tu entorno es diferente al mío!

Finalmente, adjunte la URL de la clase de herramienta relevante:
tabla de símbolos de errores:
https://bugly.qq.com/docs/release-notes/release-symboltool/?v=1.0.0

eso es todo------------------------------------------------ --------------------------------------

Supongo que te gusta

Origin blog.csdn.net/motosheep/article/details/132816991
Recomendado
Clasificación