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

相关推荐
千里马学框架2 小时前
google官方Perfetto 中使用 AI相关skill
android·人工智能·ai·framework·perfetto·性能·skill
harmful_sheep3 小时前
idea相关设置
java·ide·intellij-idea
zhangphil3 小时前
Android RecyclerView图像类ViewHolder离屏缓存数量直接增加Java/View对象内存,间接增加Graphics/GL内存
android
众少成多积小致巨3 小时前
Android C++ 编码规范指南
android·c++·google
DavidSu5 小时前
Kotlin协程原理解析
android
lxysbly5 小时前
Android PS3模拟器下载推荐2026|安卓PS3模拟器哪个好?手机玩PS3游戏指南
android·游戏·智能手机
qq_246839755 小时前
记一次 Flutter 预热帧引起的初始化问题
android·flutter
蓝冰凌5 小时前
vscode 用户级 settings.json
ide·vscode·json
阿pin5 小时前
Android随笔-要怎样与AI相处
android·人工智能·ai
Kapaseker5 小时前
Android CLI 完全指南
android·kotlin