Android SDK auto-downloadをCircleCIで有効にする

SDKのauto-download

AndroidのGradle Pluginでは2.2.0-alpha4 (2016/6/23)からSDKのauto-downloadをサポートしている。

ローカル環境で実行する場合、特に意図することなく自動でDLされるが、CI環境でそれを期待して実行するとエラーになる。

* What went wrong:
A problem occurred configuring project ':app'.
> You have not accepted the license agreements of the following SDK components:
  [Android SDK Build-Tools 25.0.2, Android SDK Platform 25].
  Before building your project, you need to accept the license agreements and complete the installation of the missing components using the Android Studio SDK Manager.
  Alternatively, to learn how to transfer the license agreements from one workstation to another, go to http://d.android.com/r/studio-ui/export-licenses.html

原因はメッセージにあるようにlicense agreementsをacceptしてないから。
リモート環境の場合は、lisenceファイルをコピーすればいいとリンク先に書いてある。(上記リンクは古く、以下にリダイレクトされる)
https://developer.android.com/studio/intro/update.html#download-with-gradle

CircleCIでlicense agreementを有効にする

さて、上記のとおりにlicenseファイルをCircleCI上に置ければいいのだが、CircleCIにはビルド時に参照出来るようなファイルを単純に置くことは出来ない。解決策としては、ぱっと思いつくので以下3通りのやり方がある。

1. ファイルをリポジトリに置く
一番簡単な方法だが、licenseファイルを公開するのはよろしくない。Privateリポジトリならいいかも

2. licenseファイルをCIサーバから参照できる場所に置いといてダウンロードする
これが一番応用が効くので良いが、今回はお手軽な方法として、次の方法を使う。

3. 環境変数を使う
licenseに同意した時に作られるファイルandroid-sdk-licenseの中身は以下のように文字列のみ

$cat android-sdk-license
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx9c55

この値をコピーして、CircleCIの環境変数に設定する。ここではANDROID_SDK_LICENSE_VALUEとした。


circle.ymlのpreセクションでandroid-sdk-licenseファイルを所定の場所に作成する

pre:
    - mkdir $ANDROID_HOME/licenses
    - echo $ANDROID_SDK_LICENSE_VALUE > $ANDROID_HOME/licenses/android-sdk-license

ちなみに、これで足りないSDKおよびBuild ToolsのDownloadは出来るようになったが、ライブラリ等のアップデートは以前と変わりなく必要になるので、全体としては以下のようになる。

  pre:
    - echo y | android update sdk --no-ui --all --filter tool,extra-android-m2repository,extra-android-support,extra-google-google_play_services,extra-google-m2repository
    - mkdir $ANDROID_HOME/licenses
    - wget $ANDROID_SDK_LICENSE_URL
    - mv android-sdk-license\?dl\=0 $ANDROID_HOME/licenses/android-sdk-license