Android获取网络状态

Android获取网络状态

学习自

  • https://developer.android.google.cn/reference/android/net/ConnectivityManager
  • http://www.cnblogs.com/qingblog/archive/2012/07/19/2598983.html

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()
}

原文地址:https://www.cnblogs.com/slyfox/p/9754619.html

时间: 2024-10-13 20:44:48

Android获取网络状态的相关文章

Delphi XE5 android 获取网络状态

unit Androidapi.JNI.Network; interface function IsConnected: Boolean; function IsWiFiConnected: Boolean; function IsMobileConnected: Boolean; implementation uses System.SysUtils, Androidapi.JNIBridge, Androidapi.JNI.GraphicsContentViewText, Androidap

android开发获取网络状态,wifi,wap,2g,3g.工具类(一)

android开发获取网络状态整理: 1 package com.gzcivil.utils; 2 3 import android.content.Context; 4 import android.net.ConnectivityManager; 5 import android.net.NetworkInfo; 6 import android.telephony.TelephonyManager; 7 import android.text.TextUtils; 8 9 public c

Android 监控网络状态

Html代码 public static boolean isNetworkAvailable(Context context) { ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity == null) { Log.i("NetWorkState", "Unavailabe

Android检查网络状态步骤

android 如何检查网络连接状态,是android开发中一个常见的问题. 获取网络信息需要在AndroidManifest.xml文件中加入相应的权限: <span style="font-size:24px;"><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> </span> 1)判断是否有网络连接 <span styl

React Native之Fetch简单封装、获取网络状态

1.Fetch的使用 fetch的使用非常简单,只需传入请求的url fetch('https://facebook.github.io/react-native/movies.json'); 当然是否请求成功与数据的处理,我们还需处理成功与失败的回调 function getMoviesFromApiAsync() { return fetch('https://facebook.github.io/react-native/movies.json') .then((response) =>

iOS 获取网络状态

在iOS开发者,获取网络状态比较常用 -(NSString *)getNetWorkStates{ UIApplication *app = [UIApplication sharedApplication]; NSArray *children = [[[app valueForKeyPath:@"statusBar"]valueForKeyPath:@"foregroundView"]subviews]; NSString *state = nil; int n

获取网络状态,区分2G3G4GWIFI等,非reachability

+(NSString *)getNetWorkStates{ UIApplication *app = [UIApplication sharedApplication]; NSArray *children = [[[app valueForKeyPath:@"statusBar"]valueForKeyPath:@"foregroundView"]subviews];    NSString *state = [[NSString alloc]init];   

Android判断网络状态方法详解

Android 判断网络状态这一应用技巧在实际应中是比较重要的.那么,在Android操作系统中,如何能够正确的判断我们所连接的网络是否断开恩?今天我们就针对这一应用技巧进行一个详细的分析. 1.public class ConnectionChangeReceiverextends BroadcastReceiver 2.{ [email protected] 4.public void onReceive( Context context,Intent intent ) 5.{ 6.Conn

微信小程序 --- 获取网络状态

获取网络状态:wx.getNetworkType btnclick:function(){ wx.getNetworkType({ success:function(res){ console.log(res); }; }); } 原文地址:https://www.cnblogs.com/e0yu/p/8489739.html