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

相关推荐
-SOLO-6 小时前
备份apk 工具
android
私人珍藏库11 小时前
【Android】BotHub-多模型AI机器人聚合库-内置免费模型
android·人工智能·智能手机·app·工具·多功能
普马萨特11 小时前
Wi-Fi 扫描频率限制与 Android 演进全解析
android
张拭心12 小时前
Android 17 新特性:后台音频交互限制加强
android·前端
张拭心12 小时前
Android 17 新特性:ProfilingManager 新触发器
android·前端
张拭心12 小时前
Android 17 新特性:MessageQueue 无锁实现
android·前端
brycegao12 小时前
如何搭建标准化 Git 工具流,保障 Android 团队代码质量
android·ci/cd
AI科技星12 小时前
数术江湖·全卷合集 - 硬核江湖・数理史诗
android·人工智能·架构·概率论·学习方法
五月君_12 小时前
安卓也支持了!微信链接 Claude Code 保姆级教程
android·微信
柚鸥ASO优化12 小时前
一篇讲透安卓ASO!开发者千万别只盯着iOS了
android·ios·aso优化