美文网首页
高版本网络监听方案更新

高版本网络监听方案更新

作者: 诡异的叶子 | 来源:发表于2021-09-09 10:19 被阅读0次

    最近在更新之前的一些java代码到kotlin去,然后把原来的NetReciever更新为kotlin版本,然后as给了我以下的错误:

    image.png image.png

    wtf?这是什么情况,仔细把提示的文字阅读一遍。。。

    image.png

    原来CONNECTIVITY_ACTION已经过时,这里官方推荐使用 requestNetwork,registerNetworkCallbackor 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

    相关文章

      网友评论

          本文标题:高版本网络监听方案更新

          本文链接:https://www.haomeiwen.com/subject/nzdiwltx.html