最近把项目升级到Android Q了,发现不少api都已经被Google标注为@Deprecated了,于是对部分API进行了适配。
适配完的方法每次在编译打包时依然还会报警告:
警告: [deprecation] ConnectivityManager中的TYPE_WIFI已过时
这个时候可以在app/build.gradle中设置:
android {
lintOptions {
checkReleaseBuilds false
abortOnError false
}
}
下次再编译就不会出现之前优化过的那些提示了,目前我是这样搞的,如有不对欢迎指正。
一、网络状态
指示网络的连接方式包括如下状态:
*TRANSPORT_CELLULAR(蜂窝网络) & TRANSPORT_WIFI & TRANSPORT_BLUETOOTH & TRANSPORT_ETHERNET & TRANSPORT_VPN & TRANSPORT_WIFI_AWARE & TRANSPORT_LOWPAN
*过时API:NetworkInfo类,全文方法阵亡
1.对手机当前是否连接网络进行优化
/**
* 当前是否连接网络
*/
fun isNetworkConnected(): Boolean {
val connectivityManager =
this.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val networkCapabilities: NetworkCapabilities? =
connectivityManager?.getNetworkCapabilities(connectivityManager.activeNetwork)
if (networkCapabilities != null) {
networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
&& networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
} else {
false
}
} else {
val networkInfo = connectivityManager?.activeNetworkInfo as NetworkInfo
networkInfo.isConnected && networkInfo.isAvailable
}
}
2.当前使用的是蜂窝网络还是WIFI等相关方法进行了优化(Bluetooth等可自行修改)
/**
* 当前使用WIFI连接网络
*/
fun currentNetWorkStatusIsWifi(): Boolean {
val systemService =
this.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val networkCapabilities: NetworkCapabilities? =
systemService?.getNetworkCapabilities(systemService.activeNetwork)
if (networkCapabilities != null) {
networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) &&
networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
} else {
false
}
} else {
val networkInfo = systemService?.activeNetworkInfo as NetworkInfo
networkInfo.isConnected && networkInfo.type == ConnectivityManager.TYPE_WIFI
}
}
/**
* 当前使用蜂窝网络连接网络
*/
fun currentNetWorkStatusIsCelluLar(): Boolean {
val connectivityManager =
this.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val networkCapabilities: NetworkCapabilities? =
connectivityManager?.getNetworkCapabilities(connectivityManager.activeNetwork)
if (networkCapabilities != null) {
networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
&& networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
&& networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
} else {
false
}
} else {
val networkInfo = connectivityManager?.activeNetworkInfo as NetworkInfo
networkInfo.isConnected && networkInfo.type == ConnectivityManager.TYPE_MOBILE
}
}