Android 网络动态监听和是否联网

一、需求描述

App内部分功能需要动态监听网络,获取网络信息,IP等,此外部分界面的功能需要检测是否联网才可跳转,于是自己总结了下。

二、网络是否连接

这个简单,一个方法就行了

 @SuppressLint("MissingPermission")
    fun isOnline(context: Context?): Boolean {
        if (context == null) {
            return false
        }
        val connectivityManager = context
            .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val activeNetwork = connectivityManager.activeNetwork ?: return false
        val networkCapabilities =
            connectivityManager.getNetworkCapabilities(activeNetwork)
        if (networkCapabilities != null) {
            return networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
        }
        return false
    }

三、动态监听网络

原理:因为当手机的网络发生变化时,广播是可以监听到的,所以可以利用这一个特性进行监听,并发送到应用所需要的地方。

第一步:设置网络类型

public enum NetworkStatus {

    NONE(-1, "no"),
   
    MOBILE(0, "mobile"),
    
    WIFI(1, "wifi");

    private int status;
    private String desc;

    NetworkStatus(int code, String msg) {
        this.status = code;
        this.desc = msg;
    }

    public int getStatus() {
        return status;
    }

    public String getDesc() {
        return desc;
    }

    @Override
    public String toString() {
        return "NetwordStatus{" +
                "status=" + status +
                ", desc='" + desc + '\'' +
                "} " + super.toString();
    }
}

第二步 新建一个广播,监听到网络变化后,发送消息

class NetworkBroadcastReceiver : BroadcastReceiver() {
    private val TAG = "NetworkBroadcastReceiver"
    private var mBroadcastCallback: NetworkBroadcastCallback? = null
    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action == null) {
            return
        }
        if (TextUtils.equals(intent.action, ConnectivityManager.CONNECTIVITY_ACTION)) {
            val isOnline = NetworkUtils.isOnline(context)
            val networkStatus = NetworkUtils.getNetWorkState(context)
            if (mBroadcastCallback != null) {
                mBroadcastCallback!!.onNetworkBroadcastCallback(isOnline, networkStatus)
            }
        }
    }


    interface NetworkBroadcastCallback {

        fun onNetworkBroadcastCallback(
            isConnected: Boolean,
            networkStatus: NetworkStatus?
        )
    }
}

第三步:新建网络监听工具类

import android.annotation.SuppressLint
import android.content.Context
import android.net.ConnectivityManager
import android.net.ConnectivityManager.NetworkCallback
import android.net.Network
import android.net.NetworkCapabilities
import android.os.Build
import com.blankj.utilcode.util.LogUtils
import com.google.android.gms.common.util.CollectionUtils
import com.lixiang..nuokesasi.delaiwen.NetworkUtils.getNetWorkState
import java.util.concurrent.CopyOnWriteArrayList


@SuppressLint("StaticFieldLeak")
object NetworkListenerHelper {
    private const val NET_TAG = "NetworkListenerHelper"
    private var mContext: Context? = null

    @SuppressLint("StaticFieldLeak")
    @Volatile
    private var mListenerList: CopyOnWriteArrayList? = null
    fun registerNetworkListener() {
        val connectivityManager =
            mContext!!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        connectivityManager.registerDefaultNetworkCallback(MyNetworkCallback())
    }


    private fun notifyAllListeners(
        isConnected: Boolean,
        networkStatus: NetworkStatus
    ) {
        if (!CollectionUtils.isEmpty(mListenerList)) {
            for (listener in mListenerList!!) {
                listener?.onNetworkConnected(isConnected, networkStatus)
            }
        }
    }


    @Synchronized
    fun addListener(listener: NetworkConnectedListener?) {
        if (listener == null) {
            return
        }
        if (mListenerList == null) {
            mListenerList = CopyOnWriteArrayList()
        }
        // 防止重复添加
        if (!mListenerList!!.contains(listener)) {
            mListenerList!!.add(listener)
        }
    }


    @Synchronized
    fun removeListener(listener: NetworkConnectedListener?) {
        if (listener != null && !CollectionUtils.isEmpty(mListenerList)) {
            mListenerList!!.remove(listener)
        }
    }

    fun unregisterNetworkCallback() {
        if (mContext == null) {
            return
        }
        val connectivityManager = mContext!!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        connectivityManager.unregisterNetworkCallback(NetworkCallback())
    }

    interface NetworkConnectedListener {
        fun onNetworkConnected(
            isConnected: Boolean,
            networkStatus: NetworkStatus?
        )
    }

    @SuppressLint("NewApi")
    private class MyNetworkCallback : NetworkCallback() {
        override fun onAvailable(network: Network) {
            super.onAvailable(network)
            val netWorkState = getNetWorkState(mContext!!)
            notifyAllListeners(true, netWorkState)
        }

        override fun onLost(network: Network) {
            super.onLost(network)
            val netWorkState = getNetWorkState(mContext!!)
            notifyAllListeners(false, netWorkState)
        }

        override fun onCapabilitiesChanged(
            network: Network,
            networkCapabilities: NetworkCapabilities
        ) {
            super.onCapabilitiesChanged(network, networkCapabilities)
            if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
                when {
                    networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
                    }
                    networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
                    }
                    else -> {
                    }
                }
            }
        }
    }

    fun init(context: Context): NetworkListenerHelper {
        mContext = context
        return this
    }
}

第四步:如何使用

1.在你的application注册监听

 NetworkListenerHelper.init(application).registerNetworkListener()

2.在你的BaseActivity里面增加监听

        NetworkListenerHelper.addListener(this)

3.使你的BaseActivity继承NetworkListenerHelper.NetworkConnectedListener并重写onNetworkConnected方法,这样当网络变化后,就会回调此方法,你就可以进行自己的逻辑处理了。

你可能感兴趣的:(Android开发,Android基础知识,android,网络)