【kotlin】コールバック をラッピングして見通し良く

なんだか微妙な感じします。

APIの仕様がなのか、

サンプルのコードがなのか、

Camera2。

android-Camera2Basic/Camera2BasicFragment.kt at master · googlesamples/android-Camera2Basic

いくつかのコールバック処理が

連続して処理されますが

kotlin の芸当で分かりやすくしてみましょう。

 

コールバックのラッピング

多くの非同期処理APIは

コールバックスタイルのインターフェースを持ってます。

suspendCoroutine の 「suspend function」 を使うと

簡単にコールバックをその中にラッピングすることができます。

簡単な例を挙げてみます。


fun longComputation(params: Params, callback: (Result) -> Unit)

longComputation という function があって、

それのコールバックは Result という計算結果を受け取ります。

これは、以下のように簡単にラッピングできます。


suspend fun longComputation(params: Params): Result = suspendCoroutine { cont ->
  longComputation(params) { cont.resume(it) }
}

分かりやすく計算結果を返し、同じ非同期ですがスレッドをブロックしません。

kotlin-coroutines/kotlin-coroutines-informal.md at master · Kotlin/kotlin-coroutines

 

コールバックのラッピング

例えば、Camera2 APIでは必須のこれ。


void openCamera (String cameraId,
                CameraDevice.StateCallback callback,
                Handler handler)

CameraManager | Android Developers

コールバックとバックグラウンドハンドラやスレッドの

準備や後始末の処理が必要ですが、

それらがあちこちに分散してしまい辛くなりますが、

Kotlin coroutine に頼ると、

きれいにラッピングできます。


suspend fun CameraManager.openCamera(cameraId: String): CameraDevice? =
  suspendCoroutine { cont ->

    val callback = object : CameraDevice.StateCallback() {

      override fun onOpened(camera: CameraDevice) {
        cont.resume(camera)
      }

      override fun onDisconnected(camera: CameraDevice) {
        cont.resume(null)
      }

      override fun onError(camera: CameraDevice, error: Int) {
        cont.resume(null)
      }
   }
   openCamera(cameraId, callback, null)
 }

android - Existing 3-function callback to Kotlin Coroutines - Stack Overflow

他のいくつかのコールバックも

同じように書き換えていくと

かなり見通しよくなります。

しかし、

このGサンプルコードは分かりづらすぎぢゃんね?


Play Services 12.0.0 で android.permission.READ_PHONE_STATE が要求されている件

Google Play Console にアップすると怒られて受け付けてくれません。

"New permissions added
WARNING
Users that have the APK with version code 19 may need to accept one or more of the android.permission.READ_PHONE_STATE and android.permission.WRITE_EXTERNAL_STORAGE permissions, which may result in them not upgrading to this version of the app."

android.permission.READ_PHONE_STATE てどんな許可内容だったか。

端末のステータスとIDの読み取り
端末の電話機能へのアクセスをアプリに許可します。これにより、電話番号、端末ID、通話中かどうか、通話相手の電話番号をアプリから特定できるようになります。

危険なパーミッションです。

「通話機能の必要ないアプリでも Play Service を利用していれば弾かれる」というような状況のようです。

android.permission.READ_PHONE_STATE added with Play Services 12.0.0 [76024034] - Visible to Public - Issue Tracker

android - Why has the READ_PHONE_STATE permission been added? - Stack Overflow

以下で回避できるようです。できました。


<uses-permission
    android:name="android.permission.READ_PHONE_STATE"
    tools:node="remove" />

なんなんでしょうね。

このような混乱はきっとこの先も増えていきそうです。

ーーー
2018-04-04: 追記
修正されているようです。
Release Notes  |  Google APIs for Android  |  Google Developers


サポートライブラリのバージョンを常に一発で揃える

こんなのでました。

All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 27.1.0, 27.0.2. Examples include com.android.support:animated-vector-drawable:27.1.0 and com.android.support:cardview-v7:27.0.2 less... (⌃F1)
There are some combinations of libraries, or tools and libraries, that are incompatible, or can lead to bugs. One such incompatibility is compiling with a version of the Android support libraries that is not the latest version (or in particular, a version lower than your targetSdkVersion.)

「com.android.support:*」のバージョンは統一しておく必要があるのでしょうが、「利用しているサポートライブラリのバージョンが違う」ということなのでしょうか。

 

依存関係の確認


$ ./gradlew app:dependencies

大量の依存関係の出力から細々と見ていきます。

という感じで古いサードパーティのライブラリなどから、

「うまくバージョンを推移させながら参照できない。」

ということなのでしょう。

 

すばやく特定する

現在の最新バージョン「27.1.0」に揃えます。

行数が多くて面倒なので、grep や sort など使って推移解決できてないものを特定します。


$ ./gradlew app:dependencies | grep com.android.support: | grep -v 27.1.0 | sort | uniq
|    +--- com.android.support:customtabs:27.0.2 (*)
|    \--- com.android.support:cardview-v7:27.0.2 (*)
|    |    +--- com.android.support:cardview-v7:27.0.2
|    |    +--- com.android.support:customtabs:27.0.2

となり

「com.android.support:customtabs」
「com.android.support:cardview-v7」

の2つであることがわかります。

この2つを build.gradle にて追加明示してあげて、sync で赤線消えます。

しかし、これもだるいですね!

 

 

Gradle ResolutionStrategy を使う

この件はサポートライブラリに関してよく遭遇するので、細かく見る方法を覚えておきながら一括な定型にしておきましょう。

force で個別よりグループまとめれば簡単でしょうか。


// build.gradle (project)

// ...

allprojects {

  // ...

  // Force all of the primary support libraries to use the same version.
  configurations.all {
    resolutionStrategy {

      // force "com.android.support:support-annotations:${versions.supportLibrary}"
      // force 'com.google.code.findbugs:jsr305:3.0.0'

      eachDependency { details ->
        if (details.requested.group == 'com.android.support') {
          details.useVersion versions.supportLibrary
        }
      }
    }
  }
}

↓ 基本的なバージョン記述は前回より

あなたの build.gradle バージョン記述、きもいです。

ResolutionStrategy - Gradle DSL Version 4.6

All com.android.support libraries must use the exact same version specification - Stack Overflow