facebook twitter hatena line email

「Android/kotlin/net」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
行1: 行1:
wifi判定
+
==wifi判定==
 
<pre>
 
<pre>
 
val networkInfo: NetworkInfo? = cm.activeNetworkInfo
 
val networkInfo: NetworkInfo? = cm.activeNetworkInfo
行6: 行6:
 
</pre>
 
</pre>
 
参考:https://www.fixes.pub/program/71288.html
 
参考:https://www.fixes.pub/program/71288.html
 +
 +
==net判定==
 +
<pre>
 +
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)
 +
}
 +
</pre>
  
 
API23以上は
 
API23以上は
 
ConnectivityManagerのactiveNetworkが使えると思うので、そちらを使う。
 
ConnectivityManagerのactiveNetworkが使えると思うので、そちらを使う。

2021年2月9日 (火) 15:46時点における版

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が使えると思うので、そちらを使う。