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

相关推荐
许杰小刀4 小时前
ctfshow-web文件包含(web78-web86)
android·前端·android studio
克里斯蒂亚诺更新8 小时前
myeclipse的pojie
java·ide·myeclipse
恋猫de小郭9 小时前
Android 上为什么主题字体对 Flutter 不生效,对 Compose 生效?Flutter 中文字体问题修复
android·前端·flutter
三少爷的鞋9 小时前
不要让调用方承担你本该承担的复杂度 —— Android Data 层设计原则
android
李李李勃谦9 小时前
Flutter 框架跨平台鸿蒙开发 - 创意灵感收集
android·flutter·harmonyos
fengci.11 小时前
ctfshow其他(web396-web407)
android
JJay.11 小时前
Android 17 大屏适配变化解
android
TE-茶叶蛋12 小时前
结合登录页-PHP基础知识点解析
android·开发语言·php
alexhilton12 小时前
Jetpack Compose元球边缘效果
android·kotlin·android jetpack