Android Weekly Notes #480 Android Weekly Issue #480

Android Weekly Issue #480

Becoming a Xoogler

一個要離開Google的人的回憶文.

Coroutine builders

suspend的方法只能被suspend的方法調用, 正常的方法不能.

最初連接正常方法和suspend的這兩個世界, 需要coroutine builder.

有三個基本的coroutine builder:

  • launch
  • runBlocking
  • async

並行進行兩個請求:

scope.launch {
    val news = async {
        newsRepo.getNews()
            .sortedByDescending { it.date }
    }
    val newsSummary = async {
        newsRepo.getNewsSummary()
    }
    view.showNews(
        newsSummary.await(),
        news.await()
    )
}

coroutineScope是一個suspend方法.
用法:

suspend fun main(): Unit = coroutineScope {
    launch {
        delay(1000L)
        println("World!")
    }
    println("Hello,")
}
// Hello,
// (1 sec)
// World!

Dagger 2 complete tutorial for beginner

Dagger 2的教程.
還有個sample: https://github.com/nlgtuankiet/dagger-basic

圖不錯.

Jetpack Compose Side-Effects I — LaunchedEffect

LaunchedEffect — Launch a coroutine tied to the scope of the composable.

如果composable退出composition, 即不再在屏幕上顯示, coroutine會取消自己.

這個例子:

@Composable
fun TimerScreen() {
    LaunchedEffect(key1 = Unit, block = {
        try {
            startTimer(5000L) { // start a timer for 5 secs
                println("Timer ended")
            }
        } catch(ex: Exception) {
                println("timer cancelled")
        }
    })
}

旋轉屏幕的時候會先取消再開始.

另一篇文章講rememberCoroutineScope: https://proandroiddev.com/jetpack-compose-side-effects-ii-remembercoroutinescope-76104d7ff09

Entity Extraction using Google’s ML Kit on Android

Google ML Kit的Entity Extraction API.

可以用來提取文字信息.

Pose estimation and classification on edge devices with MoveNet and TensorFlow Lite

姿態識別.

tensorflow的例子: https://github.com/tensorflow/examples/tree/master/lite/examples/pose_estimation/android

Working Towards Android App Excellence

  • Make app quality a cross-organizational focus — not just an engineering concern
  • Organize teams around features and/or app user journey stages
  • Use the same devices your customers use

Unbundling the WindowManager

Jetpack的WindowManager: https://developer.android.com/jetpack/androidx/releases/window

和Framework中的WindowManager功能一樣. 額外還支持了可摺疊屏和Chrome OS.

Why Workflow?

Square爲什麼要做自己的application framework.

https://github.com/square/workflow-kotlin

Seamless account transfers with Block Store

Block Store API允許你的用戶在換手機的時候在新設備上重新認證.

Block Store幫忙存儲的是authentication token.

用戶需要一個a device-to-device restore flow.

文檔: https://developers.google.com/identity/blockstore/android

Measuring Render Performance with Jetpack Compose

如何測量Compose的性能?

他們做了一些實驗, 拿了一些數據.

這裏還有一個視頻:
https://www.youtube.com/watch?v=eDcGrY_AVlw

Observing live connectivity status in Jetpack Compose

網絡狀態的觀測.

直接查看:

/**
 * Network utility to get current state of internet connection
 */
val Context.currentConnectivityState: ConnectionState
    get() {
        val connectivityManager =
            getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        return getCurrentConnectivityState(connectivityManager)
    }

private fun getCurrentConnectivityState(
    connectivityManager: ConnectivityManager
): ConnectionState {
    val connected = connectivityManager.allNetworks.any { network ->
        connectivityManager.getNetworkCapabilities(network)
            ?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
            ?: false
    }

    return if (connected) ConnectionState.Available else ConnectionState.Unavailable
}

流式觀察:

@ExperimentalCoroutinesApi
fun Context.observeConnectivityAsFlow() = callbackFlow {
    val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

    val callback = NetworkCallback { connectionState -> trySend(connectionState) }

    val networkRequest = NetworkRequest.Builder()
        .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
        .build()

    connectivityManager.registerNetworkCallback(networkRequest, callback)

    // Set current state
    val currentState = getCurrentConnectivityState(connectivityManager)
    trySend(currentState)

    // Remove callback when not used
    awaitClose {
        // Remove listeners
        connectivityManager.unregisterNetworkCallback(callback)
    }
}

fun NetworkCallback(callback: (ConnectionState) -> Unit): ConnectivityManager.NetworkCallback {
    return object : ConnectivityManager.NetworkCallback() {
        override fun onAvailable(network: Network) {
            callback(ConnectionState.Available)
        }

        override fun onLost(network: Network) {
            callback(ConnectionState.Unavailable)
        }
    }
}

界面:

@ExperimentalCoroutinesApi
@Composable
fun connectivityState(): State<ConnectionState> {
    val context = LocalContext.current
    
    // Creates a State<ConnectionState> with current connectivity state as initial value
    return produceState(initialValue = context.currentConnectivityState) {
        // In a coroutine, can make suspend calls
        context.observeConnectivityAsFlow().collect { value = it }
    }
}

是這個代碼庫裏的改動:
https://github.com/PatilShreyas/NotyKT

Supporting different screen sizes on Android with Jetpack Compose

支持多屏幕的探討.

其實還是用xml裏的尺寸然後dimenResource就好.

Code

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章