高版本网络监听方案更新
2021-09-09 本文已影响0人
诡异的叶子
最近在更新之前的一些java代码到kotlin去,然后把原来的NetReciever更新为kotlin版本,然后as给了我以下的错误:
image.png image.pngwtf?这是什么情况,仔细把提示的文字阅读一遍。。。
image.png原来CONNECTIVITY_ACTION
已经过时,这里官方推荐使用 requestNetwork
,registerNetworkCallback
or registerDefaultNetworkCallback
来替换原有的BroadcastReciever方案,既然如此,就尝试来改造一番。
首先根据不同的版本区分不同的监听方案
主方法
//网络变化监听器
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
mConnectivityManager = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
val networkCallbackImpl = NetworkCallbackImpl()
mConnectivityManager.requestNetwork(NetworkRequest.Builder().build(),networkCallbackImpl)
}else{
networkReceiver = NetWorkReciever()
val netFilter = IntentFilter()
netFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
registerReceiver(networkReceiver,netFilter)
}
NetworkCallbackImpl
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
class NetworkCallbackImpl: ConnectivityManager.NetworkCallback() {
val TAG = "NetworkCallbackImpl"
override fun onAvailable(network: Network) {
super.onAvailable(network)
Log.i(TAG,"网络已链接")
}
override fun onLost(network: Network) {
super.onLost(network)
Log.i(TAG,"网络已断开")
}
override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
super.onCapabilitiesChanged(network, networkCapabilities)
if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
when {
//WIFFI
networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
Log.i(TAG,"wifi已经连接")
}
//数据流量
networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
Log.i(TAG,"数据流量已经连接")
}
else -> {
Log.i(TAG,"其他网络")
}
}
}
}
}
然后补充一下原来NetWorkReciever
的代码
class NetWorkReciever:BroadcastReceiver() {
companion object{
const val TAG = "NetWork"
}
override fun onReceive(context: Context?, intent: Intent?) {
if(ConnectivityManager.CONNECTIVITY_ACTION==intent?.action){
//网络改变
Log.i(TAG,"NETWORK_CHANGE")
val connectivityManager =
context?.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
val info = connectivityManager.activeNetworkInfo
if (info != null && info.isConnected) {
val type = info.type
Log.i(TAG,"network isconnected ,type is $type")
} else {
Log.i(TAG,"network disconnected ,type is -1")
}
}
}
}
这里要添加两个权限到AndroidManifest.xml
下
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
再注册一下NetWorkReciever
<receiver android:name=".reciever.NetWorkReciever">
<intent-filter>
<action android:name="android.intent.action.CONNECTIVITY_CHANGE"/>
</intent-filter>
最终运行效果
image.png代码地址:https://github.com/jiaoery/MyAndroidKotlin(也有一些其他的代码学习记录)
image.png