Android Studio执行Run操作报Couldn‘t terminate previous instance of app错误

步骤1、在项目根目录下build.gradle文件最后添加如下内容

groovy 复制代码
//自定义任务名:assembleAndInstall
tasks.register('assembleAndInstall', Exec.class, new Action<Exec>() {
    @Override
    void execute(Exec exec) {
        //设置自定义任务组名
        exec.setGroup('custom task')

        //当前编译是不是release版本
        boolean isBuildRelease = false

        String buildType = 'Debug'
        if (isBuildRelease) {
            buildType = 'Release'
        }
        List<String> typeList = new ArrayList<>()
        for (final def aaa in project(':app').android.productFlavors) {
            String name = aaa['name']
            typeList.add(new String(name.charAt(0)).toUpperCase() + name.substring(1))
        }
        println 'typeList: ' + typeList.size()
        println 'typeList: ' + typeList

        //设置依赖的任务
        if (typeList.size() > 0) {
            //假设定义了两个 productFlavors,一个 phone,一个 tablet
            //默认选中第一个 tablet
            int index = 1
            exec.dependsOn('app:assemble' + typeList[index] + buildType, 'app:install' + typeList[index] + buildType)
        } else {
            //未定义productFlavors
            exec.dependsOn('app:assemble' + buildType, 'app:install' + buildType)
        }
        //获取当前连接到电脑的设备
        //exec.setCommandLine('adb', 'devices')
        //强制停止apk进程
        //exec.setCommandLine('adb', 'shell', 'am', 'force-stop', 'com.example.myapplication3')
        //启动主Activity
        exec.setCommandLine('adb', 'shell', 'am', 'start', 'com.example.myapplication3/.MainActivity')
    }
})

步骤2、修改代码同时执行该任务,gradle将会自动执行编译,编译完成后会自动将编译出来的apk安装到设备中,如果要调试的话,使用Attach Debugger to Android Process的方式即可

缺点:依旧不可以以Debug的方式安装并调试

相关推荐
聆风吟º32 分钟前
【Spring Boot 报错已解决】别让端口配置卡壳!Spring Boot “Binding to target failed” 报错解决思路
android·java·spring boot
非专业程序员Ping8 小时前
HarfBuzz概览
android·ios·swift·font
allnlei9 小时前
使用CLion进行远程开发(Remote Development)
ide·1024程序员节
Jeled9 小时前
「高级 Android 架构师成长路线」的第 1 阶段 —— 强化体系与架构思维(Clean Architecture 实战)
android·kotlin·android studio·1024程序员节
zandy10119 小时前
2025年AI IDE的深度评测与推荐:从单一功能效率转向生态壁垒
ide·人工智能
明道源码11 小时前
Kotlin 控制流、函数、Lambda、高阶函数
android·开发语言·kotlin
消失的旧时光-194313 小时前
Kotlin × Gson:为什么遍历 JsonObject 要用 entrySet()
android·kotlin·数据处理·1024程序员节
来块小鱼饼干(≧^.^≦)14 小时前
教你如何使用VSCode的EIDE插件开发STM32(包括任何ARM内核芯片)最详细教程
ide·vscode·stm32·arm·keil
G果14 小时前
安卓APP页面之间传参(Android studio 开发)
android·java·android studio
请叫我欧皇i15 小时前
保姆级教程vscode创建uniapp vue3+ts+pinia项目并实现自动导入、打包功能
ide·vscode·uni-app