zoukankan      html  css  js  c++  java
  • 判断 Android 手机是否处于联网状态

    Android App的开发大多数情况下都要与网络进行连接,那如何判断网络是否连接,处于何种连接呢?下面是关于连接写的一个方法,可以根据需求做相应的修改:

    private String connection(Context context) {
    //判断联网,一定要记得写权限<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    String connectInfo = "网络未连接";
    ConnectivityManager connect = (ConnectivityManager) context
    .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = connect.getActiveNetworkInfo();
    if(info != null && info.isConnected()){
    //if(info.isAvailable()){//此判断在使用时会有异常,需要处理
    connectInfo = "网络已经连接,";

    //GPS是否打开
    if(isGpsEnabled(this)){
    connectInfo += "GPS已经开启";
    }else {
    connectInfo += "GPS未开启";
    }

    //WiFi是否打开
    if(isWifiEnabled(this,connect)){
    connectInfo += "WIFI开启";
    }else {
    connectInfo += "WIFI未开启";
    }

    int netType = info.getType();
    if(netType == ConnectivityManager.TYPE_WIFI){
    connectInfo += " 当前使用WIFI";
    }else if(netType == ConnectivityManager.TYPE_MOBILE){
    connectInfo += " 当前使用移动连接";
    }else {
    connectInfo += " 当前使用连接是:"+netType;
    }
    }
    return connectInfo;
    }

    //判断GPS是否打开
    public static boolean isGpsEnabled(Context context) {
    LocationManager lm = ((LocationManager) context
    .getSystemService(Context.LOCATION_SERVICE));
    List<String> accessibleProviders = lm.getProviders(true);
    return accessibleProviders != null && accessibleProviders.size() > 0;
    }
    //判断WIFI是否打开
    public static boolean isWifiEnabled(Context context,ConnectivityManager mgrConn) {
    TelephonyManager mgrTel = (TelephonyManager) context
    .getSystemService(Context.TELEPHONY_SERVICE);
    return ((mgrConn.getActiveNetworkInfo() != null && mgrConn
    .getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED) || mgrTel
    .getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS);
    }
  • 相关阅读:
    oracle lengthb
    layui-rp
    1709052基于框架新建 子项目
    echar 常用单词
    Leetcode 481.神奇字符串
    Leetcode 480.滑动窗口中位数
    Leetcode 479.最大回文数乘积
    Leetcode 477.汉明距离总和
    Leetcode 476.数字的补数
    Leetcode 475.供暖气
  • 原文地址:https://www.cnblogs.com/hais/p/4689540.html
Copyright © 2011-2022 走看看