Android获取本机常用属性的工具类

项目中用到了一些Android的一些属性,就封装到一个工具类了。通过单例模式实现,可以根据自己的需求改成通过静态类。主要封装了一些常用如获取系统版本、系统分辨率、屏幕密度、IP地址、网络类型等方法。

废话不说,直接贴代码。欢迎大家指正!



import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;


/**
 * <pre>
 * 项目名称:CloudTest   
 * 类名称:DeviceInfo   
 * 类描述:  A structure describing general information about device, such as its ROM,
 * ,Serial,size, density  
 * 创建人:bd_liang   
 * 创建时间:Oct 31, 2016 5:04:04 PM   
 * 修改人:bd_liang   
 * 修改时间:Oct 31, 2016 5:04:04 PM   
 * 修改备注:
 * @version
 * 
 * 
 * <pre>
 */
public class DeviceInfo {
	private static final String TAG = DeviceInfo.class.getName();
	public static DeviceInfo mDevice;

	private static final String NET_TYPE_WIFI = "WiFi";
	private static final String NET_TYPE_4G = "4G";
	private static final String NET_TYPE_3G = "3G";
	private static final String NET_TYPE_2G = "2G";

	/**
	 * @since Android API Level 16
	 */
	private DeviceInfo() {
		mDevice = this;
	}

	/**
	 * Retrieves a singleton instance of UiDevice
	 * 
	 * @return UiDevice instance
	 */
	public static DeviceInfo getInstance() {
		if (mDevice == null) {
			synchronized (DeviceInfo.class) {
				if (mDevice == null) {
					mDevice = new DeviceInfo();
				}
			}
		}
		return mDevice;
	}

	/**
	 * Retrieves the product name of the device.
	 * 
	 * This method provides information on what type of device the test is
	 * running on. This value is the same as returned by invoking #adb shell
	 * getprop ro.product.name.
	 * 
	 * @return product name of the device
	 * @since Android API Level 17
	 */
	public String getProductName() {
		return Build.PRODUCT;
	}

	/**
	 * The user-visible version string. E.g., 5.0 or 4.4.1 etc getprop
	 * ro.build.version.release
	 * 
	 * @return
	 */
	public String getDeviceRom() {
		return Build.VERSION.RELEASE;
	}

	/**
	 ** The consumer-visible brand with which the product/hardware will be
	 * associated, if any. E.g htc or sansung getprop ro.product.brand
	 * 
	 * @return
	 */
	public String getDeviceBrand() {
		return Build.BRAND;
	}

	/**
	 * 
	 * The end-user-visible name for the end product. E.g HTC M9pw getprop
	 * ro.product.model
	 * 
	 * @return
	 */
	public String getDeviceModel() {
		return Build.MODEL;
	}

	/**
	 * A hardware serial number, if available. Alphanumeric only,
	 * case-insensitive. E.g FA54PYN02655 getprop ro.serialno
	 * 
	 * @return
	 */
	public String getDeviceSerial() {
		return Build.SERIAL;
	}

	/**
	 * A scaling factor for fonts displayed on the display. This is the same as
	 * {@link #density}, except that it may be adjusted in smaller increments at
	 * runtime based on a user preference for the font size.
	 * 
	 * @return
	 */
	public int getDeviceDensityDpi() {
		LogUtil.i(TAG, "getDeviceDensityDpi method");
		DisplayMetrics metrics = new DisplayMetrics();
		WindowManager wmManager = (WindowManager) MainApplication.getInstance()
				.getApplicationContext()
				.getSystemService(Context.WINDOW_SERVICE);

		wmManager.getDefaultDisplay().getMetrics(metrics);

		return metrics.densityDpi;
	}

	/**
	 * 获取屏幕分辨率
	 * 
	 * @return
	 */
	@SuppressLint("NewApi")
	public Point getDeviceResolution() {
		LogUtil.i(TAG, "getDeviceResolution method");
		WindowManager wmManager = (WindowManager) MainApplication.getInstance()
				.getApplicationContext()
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = wmManager.getDefaultDisplay();
		Point point = new Point();
		if (Build.VERSION.SDK_INT >= 17) {
			display.getRealSize(point);
		} else {
			display.getSize(point);
		}
		return point;
	}

	/**
	 * 获取当前网络类型,4G,WiFi等
	 * 
	 * @return
	 */
	public String getNetWorkType() {
		LogUtil.i(TAG, "getNetWorkType method");
		ConnectivityManager connectivityManager = (ConnectivityManager) MainApplication
				.getInstance().getApplicationContext()
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

		if (networkInfo == null) {
			return null;
		} else if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
			return NET_TYPE_WIFI;
		} else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
			if (networkInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_CDMA
					|| networkInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_GPRS
					|| networkInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_EDGE) {
				return NET_TYPE_2G;
			} else if (networkInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_UMTS
					|| networkInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_HSDPA
					|| networkInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_EVDO_0
					|| networkInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_EVDO_A
					|| networkInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_EVDO_B) {
				return NET_TYPE_3G;
			} else if (networkInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_LTE) {
				return NET_TYPE_4G;
			}
		}
		return null;
	}

	/**
	 * 获取应用版本号
	 * 
	 * @return
	 */
	public String getLocalVersionName(String packageName) {
		String versionName = "";
		try {
			versionName = MainApplication.getInstance().getPackageManager()
					.getPackageInfo(packageName, 0).versionName;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return versionName;
	}

	/**
	 * 获取IP地址
	 * 
	 * @return
	 */
	public String getIpAddress() {
		String type = getNetWorkType();
		if (type.equals("")) {

		} else if (type.equalsIgnoreCase("WiFi")) {
			WifiManager wifiManager = (WifiManager) MainApplication
					.getInstance().getApplicationContext()
					.getSystemService(Context.WIFI_SERVICE);
			if (wifiManager.isWifiEnabled()) {
				WifiInfo wifiInfo = wifiManager.getConnectionInfo();
				int ipAddress = wifiInfo.getIpAddress();
				return intToIp(ipAddress);
			}
		} else if (type.equalsIgnoreCase("2g") || type.equalsIgnoreCase("3g")
				|| type.equalsIgnoreCase("4g")) {
			try {
				for (Enumeration<NetworkInterface> en = NetworkInterface
						.getNetworkInterfaces(); en.hasMoreElements();) {
					NetworkInterface intf = en.nextElement();
					for (Enumeration<InetAddress> enumIpAddr = intf
							.getInetAddresses(); enumIpAddr.hasMoreElements();) {
						InetAddress inetAddress = enumIpAddr.nextElement();
						if (!inetAddress.isLoopbackAddress()
								&& inetAddress instanceof Inet4Address) {
							return inetAddress.getHostAddress();
						}
					}
				}
			} catch (SocketException ex) {
				ex.printStackTrace();
			}
		}
		return "";
	}

	/**
	 * @param i
	 * @return
	 */
	private String intToIp(int i) {
		return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
				+ "." + (i >> 24 & 0xFF);
	}

}


代码中含有另外两个类文件MainApplication.java以及LogUtil.java 涉及到具体的工程源码,不方便贴出,但是本文件中仅涉及上下文环境的获取可以自己写一个简单的MainApplication.java 文件(可参考我的另一篇介绍单例的文章里提到),logutils直接替换为Android的log工具就可用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值