当前位置:   article > 正文

Android 监听网络状态变化

android 监听网络状态变化

Android 监听网络状态变化

封装工具类

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
  • 1
  • 2
  • 3
/**
 * 网络工具类
 */
object NetworkUtils {
    // 无网络
    const val NETWORK_NONE = -1

    // wifi
    const val NETWORK_WIFI = 1

    // 3G
    const val NETWORK_2G = 2

    //3G
    const val NETWORK_3G = 3

    // 4G
    const val NETWORK_4G = 4

    // 5G
    const val NETWORK_5G = 5

    // 未知网络
    const val NETWORK_UNKNOWN = 6

    /**
     *  获取网络类型
     */
    @JvmStatic
    @RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE)
    fun getNetWorkType(context: Context): Int {
        val connectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val info = connectivityManager.activeNetworkInfo // 获取当前网络状态
        if (info != null && info.isAvailable) {
            when (info.type) {
                ConnectivityManager.TYPE_WIFI -> {
                    return NETWORK_WIFI
                }
                ConnectivityManager.TYPE_MOBILE -> {
                    when (info.subtype) {
                        TelephonyManager.NETWORK_TYPE_GSM,
                        TelephonyManager.NETWORK_TYPE_GPRS,
                        TelephonyManager.NETWORK_TYPE_CDMA,
                        TelephonyManager.NETWORK_TYPE_EDGE,
                        TelephonyManager.NETWORK_TYPE_1xRTT,
                        TelephonyManager.NETWORK_TYPE_IDEN ->
                            return NETWORK_2G
                        TelephonyManager.NETWORK_TYPE_TD_SCDMA,
                        TelephonyManager.NETWORK_TYPE_EVDO_A,
                        TelephonyManager.NETWORK_TYPE_UMTS,
                        TelephonyManager.NETWORK_TYPE_EVDO_0,
                        TelephonyManager.NETWORK_TYPE_HSDPA,
                        TelephonyManager.NETWORK_TYPE_HSUPA,
                        TelephonyManager.NETWORK_TYPE_HSPA,
                        TelephonyManager.NETWORK_TYPE_EVDO_B,
                        TelephonyManager.NETWORK_TYPE_EHRPD,
                        TelephonyManager.NETWORK_TYPE_HSPAP ->
                            return NETWORK_3G
                        TelephonyManager.NETWORK_TYPE_IWLAN,
                        TelephonyManager.NETWORK_TYPE_LTE ->
                            return NETWORK_4G
                        TelephonyManager.NETWORK_TYPE_NR ->
                            return NETWORK_5G
                        else -> {
                            val subtypeName = info.subtypeName
                            return if (subtypeName.equals("TD-SCDMA", ignoreCase = true)
                                || subtypeName.equals("WCDMA", ignoreCase = true)
                                || subtypeName.equals("CDMA2000", ignoreCase = true)
                            ) {
                                NETWORK_3G
                            } else {
                                NETWORK_UNKNOWN
                            }
                        }
                    }
                }
                else -> {
                    return NETWORK_UNKNOWN
                }
            }
        } else {
            return NETWORK_NONE
        }
    }

    /**
     * 获取网络类型名
     */
    @JvmStatic
    fun getNetWorkTypeName(context: Context): String {
        return when (getNetWorkType(context)) {
            NETWORK_WIFI -> "NETWORK_WIFI"
            NETWORK_5G -> "NETWORK_5G"
            NETWORK_4G -> "NETWORK_4G"
            NETWORK_3G -> "NETWORK_3G"
            NETWORK_2G -> "NETWORK_2G"
            NETWORK_NONE -> "NETWORK_NONE"
            else -> "NETWORK_UNKNOWN"
        }
    }

    /**
     * 判断网络连接是否可用
     */
    @JvmStatic
    fun isNetworkAvailable(context: Context): Boolean {
        val connectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        //如果仅仅是用来判断网络连接
        //则可以使用 cm.getActiveNetworkInfo().isAvailable();
        val info = connectivityManager.allNetworkInfo
        for (i in info.indices) {
            if (info[i].state == NetworkInfo.State.CONNECTED) {
                return true
            }
        }
        return false
    }

    /**
     * 判断网络是否可用
     * 需添加权限
     */
    @JvmStatic
    @RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE)
    fun isAvailable(context: Context): Boolean {
        val info = getActiveNetworkInfo(context)
        return info != null && info.isAvailable
    }

    /**
     * 判断网络是否连接
     * 需添加权限
     */
    @JvmStatic
    @RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE)
    fun isConnected(context: Context): Boolean {
        val info = getActiveNetworkInfo(context)
        return info != null && info.isConnected
    }

    /**
     * 判断是否有外网连接(普通方法不能判断外网的网络是否连接,比如连接上局域网)
     * 不要在主线程使用,会阻塞线程
     */
    @JvmStatic
    fun ping(): Boolean {
        var result: String? = null
        try {
            val ip = "www.baidu.com" // ping 的地址,可以换成任何一种可靠的外网
            val p = Runtime.getRuntime().exec("ping -c 3 -w 100 $ip") // ping网址3次
            // 读取ping的内容,可以不加
            val input = p.inputStream
            val `in` = BufferedReader(InputStreamReader(input))
            val stringBuffer = StringBuffer()
            var content: String? = ""
            while (`in`.readLine().also { content = it } != null) {
                stringBuffer.append(content)
            }
            Log.e("TAG", "result content : $stringBuffer");
            // ping的状态
            val status = p.waitFor()
            if (status == 0) {
                result = "success"
                return true
            } else {
                result = "failed"
            }
        } catch (e: IOException) {
            result = "IOException"
        } catch (e: InterruptedException) {
            result = "InterruptedException"
        } finally {
            Log.e("TAG", "result = $result");
        }
        return false
    }

    /**
     * ping IP
     * 不要在主线程使用,会阻塞线程
     */
    @JvmStatic
    fun ping(ip: String): Boolean {
        var result: String? = null
        try {
            // ping网址3次
            val p = Runtime.getRuntime().exec("ping -c 3 -w 100 $ip")
            // 读取ping的内容,可以不加
            val input = p.inputStream
            val `in` = BufferedReader(InputStreamReader(input))
            val stringBuffer = StringBuffer()
            var content: String? = ""
            while (`in`.readLine().also { content = it } != null) {
                stringBuffer.append(content)
            }
            Log.e("TAG", "result content : $stringBuffer");
            // ping的状态
            val status = p.waitFor()
            if (status == 0) {
                result = "success"
                return true
            } else {
                result = "failed"
            }
        } catch (e: IOException) {
            result = "IOException"
        } catch (e: InterruptedException) {
            result = "InterruptedException"
        } finally {
            Log.e("TAG", "result = $result");
        }
        return false
    }

    /**
     * 判断WIFI是否打开
     */
    @JvmStatic
    @RequiresPermission(Manifest.permission.ACCESS_WIFI_STATE)
    fun isWifiEnabled(context: Context): Boolean {
        val wifiManager =
            context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
        return wifiManager.isWifiEnabled
    }

    /**
     * 判断网络连接方式是否为WIFI
     */
    @JvmStatic
    fun isWifi(context: Context): Boolean {
        val networkINfo = getActiveNetworkInfo(context)
        return networkINfo != null && networkINfo.type == ConnectivityManager.TYPE_WIFI
    }

    /**
     * 判断wifi是否连接状态
     */
    @JvmStatic
    @RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE)
    fun isWifiConnected(context: Context): Boolean {
        val connectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        return connectivityManager.activeNetworkInfo != null && connectivityManager.activeNetworkInfo!!.type == ConnectivityManager.TYPE_WIFI
    }

    /**
     * 判断网络是否是4G
     */
    @JvmStatic
    @RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE)
    fun is4G(context: Context): Boolean {
        val info = getActiveNetworkInfo(context)
        return info != null && info.isAvailable && info.subtype == TelephonyManager.NETWORK_TYPE_LTE
    }

    /**
     * 判断网络是否是5G
     */
    @JvmStatic
    @RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE)
    fun is5G(context: Context): Boolean {
        val info = getActiveNetworkInfo(context)
        return (info != null && info.isAvailable && info.subtype == TelephonyManager.NETWORK_TYPE_NR)
    }

    /**
     * 判断GPS是否打开
     */
    @JvmStatic
    fun isGpsEnabled(context: Context): Boolean {
        val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        val accessibleProviders = locationManager.getProviders(true)
        return accessibleProviders.size > 0
    }

    /**
     * 打开网络设置界面
     */
    @JvmStatic
    fun openWirelessSettings(context: Context) {
//        context.startActivity(Intent(Settings.ACTION_SETTINGS)) // 跳转设置界面
        context.startActivity(Intent(Settings.ACTION_WIFI_SETTINGS)) //跳转wifi设置界面
    }

    /**
     * 获取活动网络信息
     */
    private fun getActiveNetworkInfo(context: Context): NetworkInfo? {
        val connectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        return connectivityManager.activeNetworkInfo
    }

    /**
     * 获取移动网络运营商名称
     *
     * 如中国联通、中国移动、中国电信
     *
     * @param context 上下文
     * @return 移动网络运营商名称
     */
    @JvmStatic
    fun getNetworkOperatorName(context: Context): String? {
        val telephonyManager =
            context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        return telephonyManager.networkOperatorName
    }

    /**
     * 获取移动终端类型
     *
     * @param context 上下文
     * @return 手机制式
     *
     *  * [TelephonyManager.PHONE_TYPE_NONE] : 0 手机制式未知
     *  * [TelephonyManager.PHONE_TYPE_GSM] : 1 手机制式为GSM,移动和联通
     *  * [TelephonyManager.PHONE_TYPE_CDMA] : 2 手机制式为CDMA,电信
     *  * [TelephonyManager.PHONE_TYPE_SIP] : 3
     *
     */
    @JvmStatic
    fun getPhoneType(context: Context): Int {
        val telephonyManager =
            context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        return telephonyManager.phoneType
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
/**
 *
 * 网络工具帮助类
 */
object NetworkHelper {

    private var currentNetworkType: Int = -1
    private val mListeners = hashSetOf<OnNetworkStateChangedListener>()

    fun registerListener(context: Context, listener: OnNetworkStateChangedListener) {
        val preSize = mListeners.size
        mListeners.add(listener)
        // 防止重复注册
        if (preSize == 0 && mListeners.size == 1) {
            val mFilter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
            context.registerReceiver(NetworkStateChangedReceiver, mFilter)
        }
    }

    fun isRegistered(listener: OnNetworkStateChangedListener): Boolean {
        return mListeners.contains(listener)
    }

    fun unregisterListener(context: Context, listener: OnNetworkStateChangedListener) {
        val preSize = mListeners.size
        mListeners.remove(listener)
        // 防止重复注销
        if (preSize == 1 && mListeners.size == 0) {
            context.unregisterReceiver(NetworkStateChangedReceiver)
        }
    }

    /**
     * 网络状态改变广播
     */
    object NetworkStateChangedReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (ConnectivityManager.CONNECTIVITY_ACTION == intent.action) {
                val netWorkType = NetworkUtils.getNetWorkType(context)
                if (currentNetworkType == netWorkType) {
                    return
                }
                currentNetworkType = netWorkType
                if (netWorkType == NetworkUtils.NETWORK_NONE) {
                    for (listener in mListeners) {
                        listener.onDisconnected()
                    }
                } else {
                    for (listener in mListeners) {
                        listener.onConnected(currentNetworkType)
                    }
                }
            }
        }
    }

    interface OnNetworkStateChangedListener {
        fun onDisconnected()
        fun onConnected(networkType: Int)
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61

使用

// 注册监听
NetworkHelper.registerListener(mContext, this)

// 注销监听
 NetworkHelper.unregisterListener(mContext, this)
  • 1
  • 2
  • 3
  • 4
  • 5
override fun onDisconnected() {
    Log.e(NETWORK, "当前无网络连接")
    tvNetwork.text = "当前无网络连接"
}

override fun onConnected(networkType: Int) {
    when (networkType) {
        NetworkUtils.NETWORK_WIFI -> {
            Log.e(NETWORK, "切换到wifi环境下")
            tvNetwork.text = "切换到wifi环境下"
        }
        NetworkUtils.NETWORK_2G -> {
            Log.e(NETWORK, "切换到2G环境下")
            tvNetwork.text = "切换到2G环境下"
        }
        NetworkUtils.NETWORK_3G -> {
            Log.e(NETWORK, "切换到3G环境下")
            tvNetwork.text = "切换到3G环境下"
        }
        NetworkUtils.NETWORK_4G -> {
            Log.e(NETWORK, "切换到4G环境下")
            tvNetwork.text = "切换到4G环境下"
        }
        NetworkUtils.NETWORK_5G -> {
            Log.e(NETWORK, "切换到5G环境下")
            tvNetwork.text = "切换到5G环境下"
        }
        NetworkUtils.NETWORK_UNKNOWN -> {
            Log.e(NETWORK, "未知网络")
            tvNetwork.text = "未知网络"
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/576719
推荐阅读
相关标签
  

闽ICP备14008679号