如何在build.gradle中检索ADB的路径

Dim*_*ima 15 android adb gradle gradlew android-studio

我试图通过启动应用程序gradle task.


task runDebug(dependsOn: ['installDebug', 'run']) {
}

task run(type: Exec) {
commandLine 'adb', 'shell', 'am', 'start', '-n', 'com.example.myexample/.ui.SplashScreenActivity'
}
Run Code Online (Sandbox Code Playgroud)

但是这段代码不起作用,我得到错误:
a problem occurred starting process 'command 'adb''

但是,当我明确指定adb的路径时,应用程序就会启动.


task run(type: Exec) {
    commandLine 'D:\\android\\android-studio\\sdk\\platform-tools\\adb', 'shell', 'am', 'start', '-n', 'com.example.myexample/.ui.SplashScreenActivity'
}
Run Code Online (Sandbox Code Playgroud)

那么我怎么能得到一个包含路径的变量并将其转移到commandLine

Kev*_*cke 30

您应该使用Android Gradle插件已有的逻辑来查找SDK和adb位置,以确保您的脚本使用相同的脚本.

# Android Gradle >= 1.1.0
File sdk = android.getSdkDirectory()
File adb = android.getAdbExe()

# Android Gradle < 1.1.0
File sdk = android.plugin.getSdkFolder()
File adb = android.plugin.extension.getAdbExe()
Run Code Online (Sandbox Code Playgroud)

  • 不推荐使用`getAdb`,我使用`android.getAdbExecutable().absolutePath` (4认同)

Dim*_*ima 19

问题解决了.
变量必须包含

def adb = "$System.env.ANDROID_HOME/platform-tools/adb"
Run Code Online (Sandbox Code Playgroud)

完成任务看起来像


task run(type: Exec) {
    def adb = "$System.env.ANDROID_HOME/platform-tools/adb"
    commandLine "$adb", 'shell', 'am', 'start', '-n', 'com.example.myexample/.ui.SplashScreenActivity'
}
Run Code Online (Sandbox Code Playgroud)

UPD
另一种不使用的方式ANDROID_HOME


task run(type: Exec) {
    def rootDir = project.rootDir
    def localProperties = new File(rootDir, "local.properties")
    if (localProperties.exists()) {
        Properties properties = new Properties()
        localProperties.withInputStream { 
            instr -> properties.load(instr)
        }
        def sdkDir = properties.getProperty('sdk.dir')
        def adb = "$sdkDir/platform-tools/adb"
        commandLine "$adb", 'shell', 'am', 'start', '-n', 'com.example.myexample/.ui.SplashScreenActivity'
    }
}
Run Code Online (Sandbox Code Playgroud)


Tap*_*ter 7

def androidPlugin = project.plugins.findPlugin("android")
def adb = androidPlugin.sdkHandler.sdkInfo?.adb
Run Code Online (Sandbox Code Playgroud)