NetworkUtils工具类里封装了以下方法:
- openWirelessSettings : 打开网络设置界面
- isConnected : 判断网络是否连接
- isAvailableByPing : 判断网络是否可用
- getDataEnabled : 判断移动数据是否打开
- setDataEnabled : 打开或关闭移动数据
- is4G : 判断网络是否是4G
- getWifiEnabled : 判断wifi是否打开
- setWifiEnabled : 打开或关闭wifi
- isWifiConnected : 判断wifi是否连接状态
- isWifiAvailable : 判断wifi数据是否可用
- getNetworkOperatorName : 获取移动网络运营商名称
- getNetworkType : 获取当前网络类型
- getIPAddress : 获取IP地址
- getDomainAddress : 获取域名ip地址
代码如下:
- package com.example.myapplication;
- import android.content.Context;
- import android.content.Intent;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo;
- import android.telephony.TelephonyManager;
- import java.util.ArrayList;
- import java.util.List;
- /**
- * Created by dhl on 2016/9/1.
- */
- public class NetworkUtils {
- private NetworkUtils() {
- throw new UnsupportedOperationException("u can't instance me...");
- }
- public static final int NETWORK_WIFI = 1; // wifi network
- public static final int NETWORK_4G = 4; // "4G" networks
- public static final int NETWORK_3G = 3; // "3G" networks
- public static final int NETWORK_2G = 2; // "2G" networks
- public static final int NETWORK_UNKNOWN = 5; // unknown network
- public static final int NETWORK_NO = -1; // no network
- private static final int NETWORK_TYPE_GSM = 16;
- private static final int NETWORK_TYPE_TD_SCDMA = 17;
- private static final int NETWORK_TYPE_IWLAN = 18;
- public static List<String> typeList = new ArrayList<>();
- static
- {
- typeList.add("打开网络设置界面");
- typeList.add("获取活动网络信息");
- typeList.add("判断网络是否可用");
- typeList.add("判断网络是否是4G");
- typeList.add("判断wifi是否连接状态");
- typeList.add("获取移动网络运营商名称");
- typeList.add("获取当前的网络类型");
- typeList.add("获取当前的网络类型(WIFI,2G,3G,4G)");
- }
- /**
- * 打开网络设置界面
- * <p>3.0以下打开设置界面</p>
- *
- * @param context 上下文
- */
- public static void openWirelessSettings(Context context) {
- if (android.os.Build.VERSION.SDK_INT > 10) {
- context.startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
- } else {
- context.startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
- }
- }
- /**
- * 获取活动网络信息
- *
- * @param context 上下文
- * @return NetworkInfo
- */
- public static NetworkInfo getActiveNetworkInfo(Context context) {
- ConnectivityManager cm = (ConnectivityManager) context
- .getSystemService(Context.CONNECTIVITY_SERVICE);
- return cm.getActiveNetworkInfo();
- }
- /**
- * 判断网络是否可用
- * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}</p>
- *
- * @param context 上下文
- * @return {@code true}: 可用<br>{@code false}: 不可用
- */
- public static boolean isAvailable(Context context) {
- NetworkInfo info = getActiveNetworkInfo(context);
- return info != null && info.isAvailable();
- }
- /**
- * 判断网络是否连接
- * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}</p>
- *
- * @param context 上下文
- * @return {@code true}: 是<br>{@code false}: 否
- */
- public static boolean isConnected(Context context) {
- NetworkInfo info = getActiveNetworkInfo(context);
- return info != null && info.isConnected();
- }
- /**
- * 判断网络是否是4G
- * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}</p>
- *
- * @param context 上下文
- * @return {@code true}: 是<br>{@code false}: 不是
- */
- public static boolean is4G(Context context) {
- NetworkInfo info = getActiveNetworkInfo(context);
- return info != null && info.isAvailable() && info.getSubtype() == TelephonyManager.NETWORK_TYPE_LTE;
- }
- /**
- * 判断wifi是否连接状态
- * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}</p>
- *
- * @param context 上下文
- * @return {@code true}: 连接<br>{@code false}: 未连接
- */
- public static boolean isWifiConnected(Context context) {
- ConnectivityManager cm = (ConnectivityManager) context
- .getSystemService(Context.CONNECTIVITY_SERVICE);
- return cm != null && cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;
- }
- /**
- * 获取移动网络运营商名称
- * <p>如中国联通、中国移动、中国电信</p>
- *
- * @param context 上下文
- * @return 移动网络运营商名称
- */
- public static String getNetworkOperatorName(Context context) {
- TelephonyManager tm = (TelephonyManager) context
- .getSystemService(Context.TELEPHONY_SERVICE);
- return tm != null ? tm.getNetworkOperatorName() : null;
- }
- /**
- * 获取移动终端类型
- *
- * @param context 上下文
- * @return 手机制式
- * <ul>
- * <li>{@link TelephonyManager#PHONE_TYPE_NONE } : 0 手机制式未知</li>
- * <li>{@link TelephonyManager#PHONE_TYPE_GSM } : 1 手机制式为GSM,移动和联通</li>
- * <li>{@link TelephonyManager#PHONE_TYPE_CDMA } : 2 手机制式为CDMA,电信</li>
- * <li>{@link TelephonyManager#PHONE_TYPE_SIP } : 3</li>
- * </ul>
- */
- public static int getPhoneType(Context context) {
- TelephonyManager tm = (TelephonyManager) context
- .getSystemService(Context.TELEPHONY_SERVICE);
- return tm != null ? tm.getPhoneType() : -1;
- }
- /**
- * 获取当前的网络类型(WIFI,2G,3G,4G)
- * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}</p>
- *
- * @param context 上下文
- * @return 网络类型
- * <ul>
- * <li>{@link #NETWORK_WIFI } = 1;</li>
- * <li>{@link #NETWORK_4G } = 4;</li>
- * <li>{@link #NETWORK_3G } = 3;</li>
- * <li>{@link #NETWORK_2G } = 2;</li>
- * <li>{@link #NETWORK_UNKNOWN} = 5;</li>
- * <li>{@link #NETWORK_NO } = -1;</li>
- * </ul>
- */
- public static int getNetWorkType(Context context) {
- int netType = NETWORK_NO;
- NetworkInfo info = getActiveNetworkInfo(context);
- if (info != null && info.isAvailable()) {
- if (info.getType() == ConnectivityManager.TYPE_WIFI) {
- netType = NETWORK_WIFI;
- } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
- switch (info.getSubtype()) {
- case NETWORK_TYPE_GSM:
- case TelephonyManager.NETWORK_TYPE_GPRS:
- case TelephonyManager.NETWORK_TYPE_CDMA:
- case TelephonyManager.NETWORK_TYPE_EDGE:
- case TelephonyManager.NETWORK_TYPE_1xRTT:
- case TelephonyManager.NETWORK_TYPE_IDEN:
- netType = NETWORK_2G;
- break;
- case NETWORK_TYPE_TD_SCDMA:
- case TelephonyManager.NETWORK_TYPE_EVDO_A:
- case TelephonyManager.NETWORK_TYPE_UMTS:
- case TelephonyManager.NETWORK_TYPE_EVDO_0:
- case TelephonyManager.NETWORK_TYPE_HSDPA:
- case TelephonyManager.NETWORK_TYPE_HSUPA:
- case TelephonyManager.NETWORK_TYPE_HSPA:
- case TelephonyManager.NETWORK_TYPE_EVDO_B:
- case TelephonyManager.NETWORK_TYPE_EHRPD:
- case TelephonyManager.NETWORK_TYPE_HSPAP:
- netType = NETWORK_3G;
- break;
- case NETWORK_TYPE_IWLAN:
- case TelephonyManager.NETWORK_TYPE_LTE:
- netType = NETWORK_4G;
- break;
- default:
- String subtypeName = info.getSubtypeName();
- if (subtypeName.equalsIgnoreCase("TD-SCDMA")
- || subtypeName.equalsIgnoreCase("WCDMA")
- || subtypeName.equalsIgnoreCase("CDMA2000")) {
- netType = NETWORK_3G;
- } else {
- netType = NETWORK_UNKNOWN;
- }
- break;
- }
- } else {
- netType = NETWORK_UNKNOWN;
- }
- }
- return netType;
- }
- /**
- * 获取当前的网络类型(WIFI,2G,3G,4G)
- * <p>依赖上面的方法</p>
- *
- * @param context 上下文
- * @return 网络类型名称
- * <ul>
- * <li>NETWORK_WIFI </li>
- * <li>NETWORK_4G </li>
- * <li>NETWORK_3G </li>
- * <li>NETWORK_2G </li>
- * <li>NETWORK_UNKNOWN</li>
- * <li>NETWORK_NO </li>
- * </ul>
- */
- public static String getNetWorkTypeName(Context context) {
- switch (getNetWorkType(context)) {
- case NETWORK_WIFI:
- return "NETWORK_WIFI";
- case NETWORK_4G:
- return "NETWORK_4G";
- case NETWORK_3G:
- return "NETWORK_3G";
- case NETWORK_2G:
- return "NETWORK_2G";
- case NETWORK_NO:
- return "NETWORK_NO";
- default:
- return "NETWORK_UNKNOWN";
- }
- }
- }
功能就这么多,下面是我的MainActivity的代码:
- package com.example.myapplication;
- import android.net.NetworkInfo;
- import android.support.v7.app.AppCompatActivity;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.AdapterView;
- import android.widget.Button;
- import android.widget.ListView;
- import android.widget.Switch;
- import android.widget.Toast;
- import java.util.ArrayList;
- import java.util.List;
- /**
- * 网络相关操作
- */
- public class MainActivity extends AppCompatActivity {
- private ListView listView;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- listView = (ListView)findViewById(R.id.lsit);
- listView.setAdapter(new CommonAdapter<String>(MainActivity.this,NetworkUtils.typeList,R.layout.list_item) {
- @Override
- public void convert(ViewHolder helper, String item) {
- Button button = helper.getView(R.id.network_button);
- button.setText(item);
- }
- });
- listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
- switch(NetworkUtils.typeList.get(position))
- {
- case "打开网络设置界面":
- NetworkUtils.openWirelessSettings(MainActivity.this);
- break;
- case "获取活动网络信息" :
- NetworkInfo networkInfo = NetworkUtils.getActiveNetworkInfo(MainActivity.this);
- Toast.makeText(MainActivity.this, networkInfo.toString(), Toast.LENGTH_SHORT).show();
- break;
- case "判断网络是否可用" :
- boolean isAvailable = NetworkUtils.isAvailable(MainActivity.this);
- Toast.makeText(MainActivity.this,isAvailable+"" , Toast.LENGTH_SHORT).show();
- break;
- case "判断网络是否连接" :
- boolean isConnected = NetworkUtils.isConnected(MainActivity.this);
- Toast.makeText(MainActivity.this,isConnected+"" , Toast.LENGTH_SHORT).show();
- break;
- case "判断网络是否是4G" :
- boolean is4G = NetworkUtils.is4G(MainActivity.this);
- Toast.makeText(MainActivity.this,is4G+"" , Toast.LENGTH_SHORT).show();
- break;
- case "判断wifi是否连接状态" :
- boolean isWifiConnected = NetworkUtils.isWifiConnected(MainActivity.this);
- Toast.makeText(MainActivity.this,isWifiConnected+"" , Toast.LENGTH_SHORT).show();
- break;
- case "获取移动网络运营商名称" :
- String getNetworkOperatorName = NetworkUtils.getNetworkOperatorName(MainActivity.this);
- Toast.makeText(MainActivity.this,getNetworkOperatorName+"" , Toast.LENGTH_SHORT).show();
- break;
- case "获取移动终端类型" :
- int getPhoneType = NetworkUtils.getPhoneType(MainActivity.this);
- Toast.makeText(MainActivity.this,getPhoneType+"" , Toast.LENGTH_SHORT).show();
- break;
- case "获取当前的网络类型" :
- int getNetWorkType = NetworkUtils.getNetWorkType(MainActivity.this);
- Toast.makeText(MainActivity.this,getNetWorkType+"" , Toast.LENGTH_SHORT).show();
- break;
- case "获取当前的网络类型(WIFI,2G,3G,4G)" :
- String getNetWorkTypeName = NetworkUtils.getNetWorkTypeName(MainActivity.this);
- Toast.makeText(MainActivity.this,getNetWorkTypeName+"" , Toast.LENGTH_SHORT).show();
- break;
- }
- }
- });
- }
- private void showToast()
- {
- }
- }
两个布局文件:activity_main:
- <?xml version="1.0" encoding="utf-8"?>
- <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:paddingBottom="@dimen/activity_vertical_margin"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- tools:context="com.example.myapplication.MainActivity">
- <ListView
- android:id="@+id/lsit"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- />
- </RelativeLayout>
item:
- <?xml version="1.0" encoding="utf-8"?>
- <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="wrap_content"
- android:descendantFocusability="blocksDescendants"
- >
- <Button
- android:id="@+id/network_button"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- />
- </RelativeLayout>
以及这里用到了鸿洋的通用adapter :
- package com.example.myapplication;
- import android.content.Context;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.BaseAdapter;
- import java.util.List;
- /**
- * Created by dhl on 2016/7/11.
- */
- public abstract class CommonAdapter<T> extends BaseAdapter{
- protected LayoutInflater mInflater ;
- protected Context mContext ;
- protected List<T> mDatas ;
- protected final int mItemLayoutId;
- public CommonAdapter(Context context, List<T> mDatas, int mItemLayoutId)
- {
- mInflater = LayoutInflater.from(context);
- this.mContext = context ;
- this.mDatas = mDatas;
- this.mItemLayoutId = mItemLayoutId ;
- }
- @Override
- public int getCount() {
- return mDatas.size();
- }
- @Override
- public Object getItem(int position) {
- return mDatas.get(position);
- }
- @Override
- public long getItemId(int position) {
- return position;
- }
- @Override
- public int getViewTypeCount() {
- return 2;
- }
- @Override
- public int getItemViewType(int position) {
- return position%2 ;
- }
- public int getItemLayoutIdByItemViewType(int type)
- {
- return 0;
- }
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- final ViewHolder viewHolder = getViewHolder(position ,convertView,parent);
- convert(viewHolder,mDatas.get(position));
- return viewHolder.getmConvertView();
- }
- public abstract void convert(ViewHolder helper ,T item);
- private ViewHolder getViewHolder(int position,View convertView ,ViewGroup parent)
- {
- if(mItemLayoutId != 0)
- {
- return ViewHolder.get(mContext,convertView,parent,mItemLayoutId,position);
- }else {
- return ViewHolder.get(mContext, convertView, parent, getItemLayoutIdByItemViewType(getItemViewType(position)),position);
- }
- }
- }
- package com.example.myapplication;
- import android.content.Context;
- import android.util.SparseArray;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
- /**
- * Created by dhl on 2016/7/11.
- */
- public class ViewHolder {
- private final SparseArray<View> mViews ;
- private View mConvertView ;
- private int mPosition;
- private ViewHolder(Context context, ViewGroup parent , int layoutId, int position)
- {
- this.mViews = new SparseArray<View>();
- mConvertView = LayoutInflater.from(context).inflate(layoutId,parent,false);
- mPosition = position ;
- mConvertView.setTag(this);
- }
- public static ViewHolder get(Context context ,View convertView,ViewGroup parent,
- int layoutId ,int position)
- {
- ViewHolder holder = null ;
- if(convertView == null)
- {
- holder = new ViewHolder(context,parent,layoutId,position);
- }else {
- holder = (ViewHolder) convertView.getTag();
- holder.mPosition = position;
- }
- return holder;
- }
- public <T extends View> T getView(int viewId)
- {
- View view = mViews.get(viewId);
- if(view == null)
- {
- view = mConvertView.findViewById(viewId);
- mViews.put(viewId,view);
- }
- return (T)view ;
- }
- public View getmConvertView()
- {
- return mConvertView;
- }
- public int getPosition()
- {
- return mPosition ;
- }
- }
以及最后要添加的权限:
- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>