Home > Mobile >  Wait for download file and then play sound after finish all tasks in Android Gradle
Wait for download file and then play sound after finish all tasks in Android Gradle

Time:10-13

I would like to play music when all the tasks are done. I don't know how to hook it with the last task/event.

So far I managed to download and play music and I can execute it manually.

Here is my code (mostly working):

def tempSound = "/tmp/gradleBuildFinished.wav"

task downloadMusic {
    doLast {
        println "downloadMusic"

        def sounds = [
                "http://www.xxx.zzz/hos1.wav",
                "http://www.xxx.zzz/hos2.wav",
        ]

        def r = new Random()
        def soundIndex = r.nextInt(sounds.size())

        println "Deleting temp sound: "   delete(tempSound)

        exec {
            commandLine("bash", "-c", "curl "   sounds.get(soundIndex)   " > "   tempSound)
        }
    }
}

task playMusic {
    dependsOn downloadMusic

    doLast {
        println "playMusic"

        assert file(tempSound).exists()

        ("afplay "   tempSound).execute()
    }
}

gradle.buildFinished{
    // how to execute playMusic? It will trigger when all tasks are done, right?
}

CodePudding user response:

OK, here is the answer. The main task should have been finalized by the assemble task.

def tempSound = "/tmp/gradleBuildFinished.wav"

task downloadAssembleSound() {
    doLast {
        println "> Task :downloadAssembleSound"

        def sounds = [
                "http://www.xxx.zzz/hos",
        ]

        def r = new Random()

        def soundIndex = r.nextInt(sounds.size())
        def soundNumber = r.nextInt(3)   1

        delete(tempSound)

        def sound = sounds.get(soundIndex)   soundNumber   ".wav"
        println "Fetching.... "   sound

        exec {
            commandLine("bash", "-c", "curl "   sound   " > "   tempSound)
        }
    }
}

task playAssembleSound {
    dependsOn { downloadAssembleSound }
    doLast {
        println "> Task :playAssembleSound"
        assert file(tempSound).exists()
        ("afplay "   tempSound).execute()
    }
}

tasks.whenTaskAdded { task ->
    if (task.name.contains('assemble') && task.name.contains('Debug')) {
        task.finalizedBy {
            playAssembleSound
        }
    }
}
  • Related