facebook twitter hatena line email

Android/kotlin/net

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

wifi判定

val networkInfo: NetworkInfo? = cm.activeNetworkInfo
            (networkInfo != null && networkInfo.isConnected
                    networkInfo.type == ConnectivityManager.TYPE_WIFI))

参考:https://www.fixes.pub/program/71288.html

net判定

val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    val networkCapabilities =
       connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
    return networkCapabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
       ?: false
} else {
    val networkInfo: NetworkInfo? = connectivityManager.activeNetworkInfo
    return (networkInfo != null && networkInfo.isConnected)
}

API23以上は ConnectivityManagerのactiveNetworkが使えると思うので、そちらを使う。