码迷,mamicode.com
首页 > 其他好文 > 详细

网络类型判断

时间:2015-03-16 23:03:20      阅读:290      评论:0      收藏:0      [点我收藏+]

标签:

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

一、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>

 

网络类型判断

标签:

原文地址:http://www.cnblogs.com/Dbzzcz/p/4342976.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!