zoukankan      html  css  js  c++  java
  • Android获取网络状态

    Android获取网络状态

    学习自

    Overview

    在做Android app的时候,网络的状态可能会经常的变化,当用户当前没有网络的时候,我们要保证程序不崩溃,而在当用户使用流量的话,则需要确保,在进行耗流量的操作的时候,需要给予用户警告(比如看视频,播放音乐,下载等).

    想要获取网络状态的话,我们需要通过 ConnectivityManager 类来实现,该类负责与 NetworkManagementService 系统服务进行交互来获取网络相关的信息。我们先来看一下官方文档是如何描述这个类的:

    Class that answers queries about the state of network connectivity. It also notifies applications when network connectivity changes.

    该类负责回答关于网络连接的状态的问题。 当网络连接发生改变的时候也会通知应用。

    The primary responsibilities of this class are to:
    该类的主要责任是:

    • Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)
    • 监听网络连接(Wifi,GPRS,UMTS等)
    • Send broadcast intents when network connectivity changes
    • 当网络状态发生改变的时候,发送广播
    • Attempt to "fail over" to another network when connectivity to a network is lost
    • 当网络连接丢失后,尝试连接到另一个网络
    • Provide an API that allows applications to query the coarse-grained or fine-grained state of the available networks
    • 提供一个API来允许应用查询粗粒度或细粒度的可用网络的状态
    • Provide an API that allows applications to request and select networks for their data traffic
    • 提供一个API允许应用为他们的数据流量请求或者选择网络

    可以通过下面的方式获取此类的实例

    val connectivityManager: ConnectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    
    val connectivityManager: ConnectivityManager =
            context.getSystemService(ConnectivityManager::class.java) as ConnectivityManager
    

    小贴士,请不要忘记添加 android.permission.ACCESS_NETWORK_STATE权限。

    NetworkInfo

    NetworkInfo 是一个描述网络连接状态的接口,我们主要通过这个类来获取网络的状态。

    val connectivityManager: ConnectivityManager =
            context.getSystemService(ConnectivityManager::class.java) as ConnectivityManager
    val networkInfo = connectivityManager.activeNetworkInfo
    

    常用的功能

    判断网络是否连接

    /**
     * 判断网络是否可用
     * */
    fun isAvailable(context: Context): Boolean {
        val connectivityManager: ConnectivityManager =
                context.getSystemService(ConnectivityManager::class.java) as ConnectivityManager
        val networkInfo = connectivityManager.activeNetworkInfo
        if (networkInfo != null) {
            return networkInfo.isAvailable
        }
        return false
    }
    

    判断是否是移动数据

    fun isMobile(context: Context): Boolean {
        val connectivityManager: ConnectivityManager =
                context.getSystemService(ConnectivityManager::class.java) as ConnectivityManager
        val networkInfo = connectivityManager.activeNetworkInfo
        if (networkInfo != null) {
            return networkInfo.type == ConnectivityManager.TYPE_MOBILE
        }
        return false
    }
    

    监听网络的变化

    从官方文档我们可以知道,如果要想监听到网络的变化的,那么需要我们动态注册一个广播才行。

    val networkStatusChangeReceiver = object : BroadcastReceiver() {
        @SuppressLint("ServiceCast")
        override fun onReceive(context: Context?, intent: Intent?) {
            val connectivityManager: ConnectivityManager =
                    context!!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val networkInfo = connectivityManager.activeNetworkInfo
            if (networkInfo != null && networkInfo.isAvailable) {
                tvNetworkStatus.text = "Current Network Status: Available"
            } else {
                tvNetworkStatus.text = "Current Network Status: unavailable"
            }
        }
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //注册一个广播
        val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
        this.registerReceiver(this.networkStatusChangeReceiver, filter)
    }
    
    override fun onDestroy() {
        this.unregisterReceiver(this.networkStatusChangeReceiver)
        super.onDestroy()
    }
    
  • 相关阅读:
    bzoj4033
    bzoj 1197
    bzoj 1196
    bzoj 1195
    bzoj 1194
    bzoj 1193
    bzoj 1192
    jvm系列(一):java类的加载机制
    红黑树之 原理和算法详细介绍
    TreeMap详细介绍(源码解析)和使用示例
  • 原文地址:https://www.cnblogs.com/slyfox/p/9754619.html
Copyright © 2011-2022 走看看