网络类型判断

判断当前所用网络的状态,包括主动判断和当网络变化时的被动判断

一、MainActivity.java

package com.example.networklistener;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.MenuItem;
import android.view.TextureView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private TextView tv_network;
    private NetStateChangedReceiver receiver;
    private LinearLayout ll_network;
    private ScrollView sv_network;
    private Timer timer;
    private String frontName = "无";
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            showNetWork(false);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setupView();
        addListener();
        initReceiver();
        setData();
    }

    private void initReceiver() {
        receiver = new NetStateChangedReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        registerReceiver(receiver, filter);
    }

    private void setupView() {
        tv_network = (TextView) findViewById(R.id.tv_network);
        ll_network = (LinearLayout) findViewById(R.id.ll_network);
        sv_network = (ScrollView) findViewById(R.id.sv_network);
    }

    private void addListener() {

    }

    private void setData() {
        timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                handler.sendEmptyMessage(0);
            }
        }, 1000, 20 * 1000);
    }

    public class NetStateChangedReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            showNetWork(true);
        }

    }

    private void showNetWork(boolean BDflag) {
        View view = View.inflate(this, R.layout.item_network, null);
        TextView tv_type = (TextView) view.findViewById(R.id.tv_type);
        TextView tv_state = (TextView) view.findViewById(R.id.tv_state);
        TextView tv_clz = (TextView) view.findViewById(R.id.tv_clz);
        TextView tv_time = (TextView) view.findViewById(R.id.tv_time);

        if (BDflag) {
            tv_clz.setText("被动");
        } else {
            tv_clz.setText("主动");
            tv_clz.setTextColor(0xff2D8841);
        }
        String time = new SimpleDateFormat("yyyy_MM_dd HH:mm:ss")
                .format(new Date());
        tv_time.setText(time);
        tv_state.setText("已连接");
        int netType = NetTypeUtil.getNetWorkType(this);
        switch (netType) {
        case NetTypeUtil.NETWORKTYPE_INVALID:
            if (BDflag) {
                tv_type.setText(frontName);
                tv_state.setText("断开");
            } else {
                tv_type.setText("无");
                tv_state.setText("*");
            }
            break;
        case NetTypeUtil.NETWORKTYPE_WAP:
            tv_type.setText("WAP");
            break;
        case NetTypeUtil.NETWORKTYPE_2G:
            tv_type.setText("2G");
            break;
        case NetTypeUtil.NETWORKTYPE_3G:
            tv_type.setText("3G");
            break;
        case NetTypeUtil.NETWORKTYPE_WIFI:
            tv_type.setText("WIFI");
            break;
        }
        frontName = tv_type.getText().toString();

        ll_network.addView(view);
        new Handler().post(new Runnable() {

            @Override
            public void run() {
                moveUI();
            }
        });
    }

    /**
     * ui重构
     */
    private void moveUI() {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                int svHeight = sv_network.getHeight();
                int llHeight = ll_network.getHeight();
                if (llHeight > svHeight) {
                    int moveY = llHeight - svHeight;
                    sv_network.scrollTo(0, moveY);
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId()) {
        case R.id.item_start:
            if (timer != null) {
                timer.cancel();
            }
            setData();
            break;
        case R.id.item_stop:
            timer.cancel();
            timer = null;
            break;
        case R.id.item_clear:
            ll_network.removeAllViews();
            break;
        default:
            break;
        }
        return super.onMenuItemSelected(featureId, item);
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);
        super.onDestroy();
    }
}

二、NetTypeUtil.java

package com.example.networklistener;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

public class NetTypeUtil {
    /** 没有网络 */
    public static final int NETWORKTYPE_INVALID = 0;
    /** wap网络 */
    public static final int NETWORKTYPE_WAP = 1;
    /** 2G网络 */
    public static final int NETWORKTYPE_2G = 2;
    /** 3G和3G以上网络,或统称为快速网络 */
    public static final int NETWORKTYPE_3G = 3;
    /** wifi网络 */
    public static final int NETWORKTYPE_WIFI = 4;

    private static boolean isFastMobileNetwork(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        switch (telephonyManager.getNetworkType()) {
        case TelephonyManager.NETWORK_TYPE_1xRTT:
            return false; // ~ 50-100 kbps
        case TelephonyManager.NETWORK_TYPE_CDMA:
            return false; // ~ 14-64 kbps
        case TelephonyManager.NETWORK_TYPE_EDGE:
            return false; // ~ 50-100 kbps
        case TelephonyManager.NETWORK_TYPE_EVDO_0:
            return true; // ~ 400-1000 kbps
        case TelephonyManager.NETWORK_TYPE_EVDO_A:
            return true; // ~ 600-1400 kbps
        case TelephonyManager.NETWORK_TYPE_GPRS:
            return false; // ~ 100 kbps
        case TelephonyManager.NETWORK_TYPE_HSDPA:
            return true; // ~ 2-14 Mbps
        case TelephonyManager.NETWORK_TYPE_HSPA:
            return true; // ~ 700-1700 kbps
        case TelephonyManager.NETWORK_TYPE_HSUPA:
            return true; // ~ 1-23 Mbps
        case TelephonyManager.NETWORK_TYPE_UMTS:
            return true; // ~ 400-7000 kbps
        case TelephonyManager.NETWORK_TYPE_EHRPD:
            return true; // ~ 1-2 Mbps
        case TelephonyManager.NETWORK_TYPE_EVDO_B:
            return true; // ~ 5 Mbps
        case TelephonyManager.NETWORK_TYPE_HSPAP:
            return true; // ~ 10-20 Mbps
        case TelephonyManager.NETWORK_TYPE_IDEN:
            return false; // ~25 kbps
        case TelephonyManager.NETWORK_TYPE_LTE:
            return true; // ~ 10+ Mbps
        case TelephonyManager.NETWORK_TYPE_UNKNOWN:
            return false;
        default:
            return false;
        }
    }

    /**
     * 获取网络状态,wifi,wap,2g,3g.
     *
     * @param context
     *            上下文
     * @return int 网络状态 {@link #NETWORKTYPE_2G},{@link #NETWORKTYPE_3G}, *
     *         {@link #NETWORKTYPE_INVALID},{@link #NETWORKTYPE_WAP}*
     *         <p>
     *         {@link #NETWORKTYPE_WIFI}
     */

    public static int getNetWorkType(Context context) {
        int mNetWorkType = -1;

        ConnectivityManager manager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isConnected()) {
            String type = networkInfo.getTypeName();

            if (type.equalsIgnoreCase("WIFI")) {
                mNetWorkType = NETWORKTYPE_WIFI;
            } else if (type.equalsIgnoreCase("MOBILE")) {
                String proxyHost = android.net.Proxy.getDefaultHost();

                mNetWorkType = TextUtils.isEmpty(proxyHost) ? (isFastMobileNetwork(context) ? NETWORKTYPE_3G
                        : NETWORKTYPE_2G)
                        : NETWORKTYPE_WAP;
            }
        } else {
            mNetWorkType = NETWORKTYPE_INVALID;
        }

        return mNetWorkType;
    }
}

三、activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    tools:context=".MainActivity" >

    <LinearLayout
        android:id="@+id/ll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:text="网络类型"
            android:textColor="#4228A4"
            android:textSize="16sp"
            android:textStyle="bold" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:text="网络状态"
            android:textColor="#4228A4"
            android:textSize="16sp"
            android:textStyle="bold" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal"
            android:text="获取方式"
            android:textColor="#4228A4"
            android:textSize="16sp"
            android:textStyle="bold" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:gravity="center_horizontal"
            android:text="开启时间"
            android:textColor="#4228A4"
            android:textSize="16sp"
            android:textStyle="bold" />
    </LinearLayout>

    <ScrollView
        android:id="@+id/sv_network"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/ll" >

        <LinearLayout
            android:id="@+id/ll_network"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/tv_network"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textColor="#8170C4"
                android:textSize="16sp" />
        </LinearLayout>
    </ScrollView>

</RelativeLayout>

四、item_network.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/tv_type"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center_horizontal"
        android:text="TextView"
        android:textColor="#8170C4"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/tv_state"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center_horizontal"
        android:text="TextView"
        android:textColor="#8170C4"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/tv_clz"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center_horizontal"
        android:textColor="#A015A0"
        android:text="TextView"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/tv_time"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:gravity="center_horizontal"
        android:text="TextView"
        android:textColor="#8170C4"
        android:textSize="16sp" />

</LinearLayout>
时间: 2025-01-16 06:02:00

网络类型判断的相关文章

Android网络类型判断(2g、3g、wifi)

判断网络类型是wifi,还是3G,还是2G网络,对不同 的网络进行不同的处理,现将判断方法整理给大家,以供参考 说明:下面用到的数据移动2G,联通2G,联通3G,wifi我都已经测试过,暂时手上 没有电信的卡,所以没有验证,有电信手机的同事,可以验证一下,验证后将结果 发送给大家. ConnectivityManager connectMgr = (ConnectivityManager) this .getSystemService(Context.CONNECTIVITY_SERVICE);

Android 网络连接判断与处理

Android网络连接判断与处理 获取网络信息需要在AndroidManifest.xml文件中加入相应的权限. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 1)判断是否有网络连接 复制代码 1 public boolean isNetworkConnected(Context context) { 2     if (context != null) { 3    

Android网络连接判断与处理

获取网络信息需要在AndroidManifest.xml文件中加入相应的权限. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 1)判断是否有网络连接 1 public boolean isNetworkConnected(Context context) { 2 if (context != null) { 3 ConnectivityManager mConnectiv

Android 网络连接判断并进行相关处理

获取网络信息需要在AndroidManifest.xml文件中加入相应的权限. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 1)判断是否有网络连接,没有则进入网络设置 /** * 检测网络是否连接 * @return */ private boolean checkNetworkState() { boolean flag = false; //得到网络连接信息 man

android如何判断当前网络类型(联网,2g,3g,wifi等)

一般对网络的判断都是判断是否联网,不过有时候我们需要知道具体的网络类型,比如在3g网络下,百度地图的定位功能存在很大的偏差,这就需要提前判断网络类型针对3g网络情况做特殊的处理. 关于Android如何检测网络的类型,网上代码很多,但是有用的不多,真正解决了问题的我只找到一篇(见文章末尾网址),为了更好的方便自己理解,对这片文章做了解释和整理. 在android中判断网络需要用到ConnectivityManager,下面的方法演示了如何用ConnectivityManager判断当前是否联网:

Android 判断网络类型

//判断网络类型 ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); //判断当前的网络连接类型 NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if (!networkInfo.isAvailable()) return; //获取当前网络的类型 S

Android判断网络类型以及监控网络状态

一.判断网络类型是wifi,还是3G,还是2G网络 ConnectivityManager connectMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = connectMgr.getActiveNetworkInfo(); 一.判断网络是否是wifi,在判断之前一定要进行的非空判断,如果没有任何网络 连接info ==null info.getT

iOS 判断当前是否连接到网络和网络类型

之前有判断过是否连接到网络,没有使用apple的示例中的Reachability. #import <sys/socket.h> #import <netinet/in.h> #import <arpa/inet.h> #import <SystemConfiguration/SCNetworkReachability.h> -(BOOL)isConnectToNewtwork { struct sockaddr_in zeroAddress; bzero(

android当前网络连接类型判断

package net.nyist.netState; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; /**@author * *这是一个判断当前网络状态的工具类 * */ public class netState { /** * * @return 是否有活动的网络连接 */ public final boolean hasNetW