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的方式安装并调试

相关推荐
三少爷的鞋几秒前
毁掉 Android 现代架构,只需要一个自定义的“FlowBus”
android
jack1868912 小时前
安卓手机忘记锁屏密码怎么办? 无需密码也可解锁
android·智能手机
应用市场15 小时前
不用一张图片的像素小游戏:小人是字符串,房间是矩形,平衡靠两千个假玩家
android·kotlin·游戏开发
葵花日记15 小时前
VS2022 美化指南:用 ClaudiaIDE 设置自定义编辑器背景
ide·visualstudio·编辑器
stevenzqzq15 小时前
android 对渠道的理解
android
QEasycloud16 小时前
BOM接口抛转失败钉钉通知策略实战教程:MySQL异常日志到钉钉消息的端到端配置
android·mysql·钉钉
AIsoft_868916 小时前
医患交流内容如何做好记录?
android·iphone
解道Jdon16 小时前
FigCraft把Figma用Rust从零重写了一遍
ide·windows·git·svn·eclipse·github·visual studio
蒸鱼Yuzheng16 小时前
Android Native 崩溃证据链:Tombstone、Build ID 与 Trace 如何联合归因
android·ndk·tombstone·调试符号·崩溃分析
事圆则缓16 小时前
Kotlin 变量与函数:把页面状态和行为写成清楚的契约
android·开发语言·kotlin