package cn.net.caoyao.cpzshandset.common.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.format.Formatter;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import cn.net.caoyao.cpzshandset.bean.HandsetParameterBean;

public class PhoneParameterUtils {
	// private static final String TAG = "echo";
	@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
	public static HandsetParameterBean getHandsetParameter(Context context) {
		HandsetParameterBean pBean = new HandsetParameterBean();
		final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		String android_id = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
		pBean.setImei(tm.getDeviceId());
		pBean.setMac(getMacAddress(context));
		pBean.setSerial(Build.SERIAL);
		pBean.setBrand(Build.BRAND);
		pBean.setAndroidReleaseVersion(Build.VERSION.RELEASE);
		pBean.setCpuName(getCpuName());
		pBean.setWifiIp(getlocalip(context));
		pBean.setAppInfos(getAllApp(context));
		// ----------------------------内存相关----------------------------------------
		ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();

		mActivityManager.getMemoryInfo(mi);
		long mTotalMem = 0;
		long mAvailMem = mi.availMem;
		String str1 = "/proc/meminfo";
		String str2;
		String[] arrayOfString;
		try {
			FileReader localFileReader = new FileReader(str1);
			BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);
			str2 = localBufferedReader.readLine();
			arrayOfString = str2.split("\\s+");
			mTotalMem = Long.valueOf(arrayOfString[1]).longValue() * 1024;
			localBufferedReader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		pBean.setMemoryTotalCapacity(mTotalMem);
		pBean.setMemoryTotalCapacityDes(Formatter.formatFileSize(context, mTotalMem));
		pBean.setMemoryAvailableCapacity(mAvailMem);
		pBean.setMemoryAvailableCapacityDes(Formatter.formatFileSize(context, mAvailMem));
		// ----------------------------sdcard相关----------------------------------------
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			File sdcardDir = Environment.getExternalStorageDirectory();
			StatFs sf = new StatFs(sdcardDir.getPath());
//			long blockSize;
//			if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){
//				blockSize = sf.getBlockSizeLong();
//			}else {
//				blockSize = sf.getBlockSize();
//			}
			long blockSize = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 ? sf.getBlockSizeLong() : sf.getBlockSize());
			long blockCount = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 ? sf.getBlockCountLong() : sf.getBlockCount());
//			long blockCount = sf.getBlockCountLong();
//			long availCount = sf.getAvailableBlocksLong();
			long availCount = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 ?sf.getAvailableBlocksLong() : sf.getAvailableBlocks());
			pBean.setSdcardTotalCapacity(blockSize * blockCount);
			pBean.setSdcardTotalCapacityDes(Formatter.formatFileSize(context, blockSize * blockCount));
			pBean.setSdcardAvailableCapacity(availCount * blockSize);
			pBean.setSdcardAvailableCapacityDes(Formatter.formatFileSize(context, availCount * blockSize));
		}
		// ----------------------------sys存储相关----------------------------------------
        File root = Environment.getRootDirectory(); 
        StatFs sf1 = new StatFs(root.getPath()); 
        long blockSize1 = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 ? sf1.getBlockSizeLong():sf1.getBlockSize()); 
        long blockCount1 = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 ? sf1.getBlockCountLong():sf1.getBlockCount()); 
        long availCount1 = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 ? sf1.getAvailableBlocksLong():sf1.getAvailableBlocks()); 
        pBean.setSysTotalCapacity(blockSize1*blockCount1);
        pBean.setSysTotalCapacityDes(Formatter.formatFileSize(context, blockSize1*blockCount1));
        pBean.setSysAvailableCapacity(availCount1*blockSize1);
        pBean.setSysAvailableCapacityDes(Formatter.formatFileSize(context, availCount1*blockSize1));
		
		return pBean;
	}

	/**
	 * IMEI号，IESI号，手机型号
	 */
	private static void getInfo(Context context) {
		TelephonyManager mTm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		String imei = mTm.getDeviceId();
		String imsi = mTm.getSubscriberId();
		String mtype = android.os.Build.MODEL; // 手机型号
		String number = mTm.getLine1Number(); // 手机号码，有的可得，有的不可得
		// LogUtil.d(TAG, "getInfo-- imei:" + imei +"\n imsi:" +imsi + "/n
		// mtype:" + mtype +"/n number:" + number) ;
	}
	// 获取CPU名字

	public static String getCpuName() {

		try {

			FileReader fr = new FileReader("/proc/cpuinfo");

			BufferedReader br = new BufferedReader(fr);

			String text = br.readLine();

			String[] array = text.split(":\\s+", 2);

			for (int i = 0; i < array.length; i++) {

			}

			return array[1];

		} catch (FileNotFoundException e) {

			e.printStackTrace();

		} catch (IOException e) {

			e.printStackTrace();

		}

		return null;

	}

	/**
	 * cpu 使用情况
	 * 
	 * @return
	 */
	public static List<String> getCpuInfo() {
		List<String> cpuInfos = new ArrayList<>();
		String str1 = "/proc/cpuinfo";
		String str2 = "";
		String[] cpuInfo = { "", "" }; // 1-cpu型号 //2-cpu频率
		String[] arrayOfString;
		try {
			FileReader fr = new FileReader(str1);
			BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
			str2 = localBufferedReader.readLine();
			arrayOfString = str2.split("\\s+");
			for (int i = 2; i < arrayOfString.length; i++) {
				cpuInfo[0] = cpuInfo[0] + arrayOfString[i] + " ";
			}
			str2 = localBufferedReader.readLine();
			arrayOfString = str2.split("\\s+");
			cpuInfo[1] += arrayOfString[2];
			localBufferedReader.close();
		} catch (IOException e) {
		}
		// LogUtil.i(TAG, "cpuinfo:" + cpuInfo[0] + " " + cpuInfo[1]);
		cpuInfos.add("CPU型号 :" + cpuInfo[0]);
		cpuInfos.add("CPU频率:" + cpuInfo[1]);
		return cpuInfos;
	}

	/**
	 * 获取手机CPU信息
	 * 
	 * @return
	 */
	/*
	 * public String[] getCpuInfo() { String str1 = "/proc/cpuinfo"; String str2
	 * = ""; String[] cpuInfo = { "", "" }; String[] arrayOfString; try {
	 * FileReader fr = new FileReader(str1); BufferedReader localBufferedReader
	 * = new BufferedReader(fr, 8192); str2 = localBufferedReader.readLine();
	 * arrayOfString = str2.split("\\s+"); for (int i = 2; i <
	 * arrayOfString.length; i++) { cpuInfo[0] = cpuInfo[0] + arrayOfString[i] +
	 * " "; } str2 = localBufferedReader.readLine(); arrayOfString =
	 * str2.split("\\s+"); cpuInfo[1] += arrayOfString[2];
	 * localBufferedReader.close(); } catch (IOException e) { }
	 * tvHardwareInfo.append("CPU型号 " + cpuInfo[0] + "\n" + "CPU频率: " +
	 * cpuInfo[1] + "\n"); return cpuInfo; }
	 */
	/**
	 * 获取当前CPU占比 在实际测试中发现，有的手机会隐藏CPU状态，不会完全显示所有CPU信息，例如MX5，所有建议只做参考
	 * 
	 * @return
	 */
	public static String getCPURateDesc() {
		String path = "/proc/stat";// 系统CPU信息文件
		long totalJiffies[] = new long[2];
		long totalIdle[] = new long[2];
		int firstCPUNum = 0;// 设置这个参数，这要是防止两次读取文件获知的CPU数量不同，导致不能计算。这里统一以第一次的CPU数量为基准
		FileReader fileReader = null;
		BufferedReader bufferedReader = null;
		Pattern pattern = Pattern.compile(" [0-9]+");
		for (int i = 0; i < 2; i++) {
			totalJiffies[i] = 0;
			totalIdle[i] = 0;
			try {
				fileReader = new FileReader(path);
				bufferedReader = new BufferedReader(fileReader, 8192);
				int currentCPUNum = 0;
				String str;
				while ((str = bufferedReader.readLine()) != null && (i == 0 || currentCPUNum < firstCPUNum)) {
					if (str.toLowerCase().startsWith("cpu")) {
						currentCPUNum++;
						int index = 0;
						Matcher matcher = pattern.matcher(str);
						while (matcher.find()) {
							try {
								long tempJiffies = Long.parseLong(matcher.group(0).trim());
								totalJiffies[i] += tempJiffies;
								if (index == 3) {// 空闲时间为该行第4条栏目
									totalIdle[i] += tempJiffies;
								}
								index++;
							} catch (NumberFormatException e) {
								e.printStackTrace();
							}
						}
					}
					if (i == 0) {
						firstCPUNum = currentCPUNum;
						try {// 暂停50毫秒，等待系统更新信息。
							Thread.sleep(50);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				if (bufferedReader != null) {
					try {
						bufferedReader.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		double rate = -1;
		if (totalJiffies[0] > 0 && totalJiffies[1] > 0 && totalJiffies[0] != totalJiffies[1]) {
			rate = 1.0 * ((totalJiffies[1] - totalIdle[1]) - (totalJiffies[0] - totalIdle[0]))
					/ (totalJiffies[1] - totalJiffies[0]);
		}

		return String.format("cpu:%.2f", rate);
	}

	public static float getProcessCpuRate() {

		float totalCpuTime1 = getTotalCpuTime();
		float processCpuTime1 = getAppCpuTime();
		try {
			Thread.sleep(360);

		} catch (Exception e) {
		}

		float totalCpuTime2 = getTotalCpuTime();
		float processCpuTime2 = getAppCpuTime();

		float cpuRate = 100 * (processCpuTime2 - processCpuTime1) / (totalCpuTime2 - totalCpuTime1);

		return cpuRate;
	}

	public static long getTotalCpuTime() { // 获取系统总CPU使用时间
		String[] cpuInfos = null;
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("/proc/stat")), 1000);
			String load = reader.readLine();
			reader.close();
			cpuInfos = load.split(" ");
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		long totalCpu = Long.parseLong(cpuInfos[2]) + Long.parseLong(cpuInfos[3]) + Long.parseLong(cpuInfos[4])
				+ Long.parseLong(cpuInfos[6]) + Long.parseLong(cpuInfos[5]) + Long.parseLong(cpuInfos[7])
				+ Long.parseLong(cpuInfos[8]);
		return totalCpu;
	}

	public static long getAppCpuTime() { // 获取应用占用的CPU时间
		String[] cpuInfos = null;
		try {
			int pid = android.os.Process.myPid();
			// BufferedReader reader = new BufferedReader(new
			// InputStreamReader(new FileInputStream("/proc/" + pid + "/stat")),
			// 1000);
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(new FileInputStream("/proc/" + pid + "/stat")), 1000);

			String load = reader.readLine();
			reader.close();
			cpuInfos = load.split(" ");
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		long appCpuTime = Long.parseLong(cpuInfos[13]) + Long.parseLong(cpuInfos[14]) + Long.parseLong(cpuInfos[15])
				+ Long.parseLong(cpuInfos[16]);
		return appCpuTime;
	}

	/**
	 * 获取系统容量的使用情况
	 * 
	 * @return
	 */
	public static String getSystemInfo(Context context) {
		String systemInfo = "";
		File root = Environment.getRootDirectory();
		StatFs sf = new StatFs(root.getPath());
		long blockSize = sf.getBlockSize();
		long blockCount = sf.getBlockCount();
		long availCount = sf.getAvailableBlocks();
		// Log.d("", "block大小:"+ blockSize+",block数目:"+
		// blockCount+",总大小:"+blockSize*blockCount/1024+"KB");
		// Log.d("", "可用的block数目：:"+ availCount+",可用大小:"+
		// availCount*blockSize/1024+"KB");
		// systemInfo = "block大小:"+ blockSize+",block数目:"+
		// blockCount+",总大小:"+blockSize*blockCount/1024+"KB" +"/n" +
		// "可用的block数目：:"+ availCount+",可用大小:"+ availCount*blockSize/1024+"KB";
		systemInfo = "总大小:" + Formatter.formatFileSize(context, blockSize * blockCount) + "\n" + "可用大小:"
				+ Formatter.formatFileSize(context, availCount * blockSize);

		return systemInfo;
	}

	/**
	 * 获取sd卡的使用情况
	 * 
	 * @return
	 */
	public static String getSDCardInfo(Context context) {
		String sdInfo = "";
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			File sdcardDir = Environment.getExternalStorageDirectory();
			StatFs sf = new StatFs(sdcardDir.getPath());
			long blockSize = sf.getBlockSize();
			long blockCount = sf.getBlockCount();
			long availCount = sf.getAvailableBlocks();
			// Log.d(TAG, "block大小:"+ blockSize+",block数目:"+
			// blockCount+",总大小:"+blockSize*blockCount/1024+"KB");
			// Log.d(TAG, "可用的block数目：:"+ availCount+",剩余空间:"+
			// availCount*blockSize/1024+"KB");
			// Formatter.formatFileSize(context, mTotalMem)
			// sdInfo = "block大小:"+ blockSize+",block数目:"+
			// blockCount+",总大小:"+blockSize*blockCount/1024+"KB" + "\n"
			// +"可用的block数目：:"+ availCount+",剩余空间:"+
			// availCount*blockSize/1024+"KB";
			// sdInfo = "block大小:"+ Formatter.formatFileSize(context,
			// blockSize)+",block数目:"+ blockCount+",总大小:"+
			// Formatter.formatFileSize(context, blockSize*blockCount)+ "\n"
			// +"可用的block数目：:"+ availCount+",剩余空间:"+
			// Formatter.formatFileSize(context, availCount*blockSize);
			sdInfo = "总大小:" + Formatter.formatFileSize(context, blockSize * blockCount) + "\n" + "剩余空间:"
					+ Formatter.formatFileSize(context, availCount * blockSize);
		}

		return sdInfo;
	}

	/**
	 * 内存的使用情况
	 * 
	 * @param context
	 * @return
	 */
	public static List<String> getTotalMemory(Context context) {
		List<String> memoryInfo = new ArrayList<>();
		String[] result = { "", "" }; // 1-total 2-avail
		ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();

		mActivityManager.getMemoryInfo(mi);
		long mTotalMem = 0;
		long mAvailMem = mi.availMem;
		String str1 = "/proc/meminfo";
		String str2;
		String[] arrayOfString;
		try {
			FileReader localFileReader = new FileReader(str1);
			BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);
			str2 = localBufferedReader.readLine();
			arrayOfString = str2.split("\\s+");
			mTotalMem = Long.valueOf(arrayOfString[1]).longValue() * 1024;
			localBufferedReader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		result[0] = Formatter.formatFileSize(context, mTotalMem);
		result[1] = Formatter.formatFileSize(context, mAvailMem);
		memoryInfo.add("总容量：" + result[0]);
		memoryInfo.add("可使用：" + result[1]);
		// Log.i(TAG, "meminfo total:" + result[0] + " used:" + result[1]);
		return memoryInfo;
	}

	public static String phoneInfo(Context context) {
		final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

		String android_id = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);

		StringBuilder sb = new StringBuilder();
		sb.append("========TelephonyManager类============" + "\n");
		sb.append("imei== " + tm.getDeviceId() + "\n");
		sb.append("手机号码= " + tm.getLine1Number() + "\n");
		sb.append("网络国家iso= " + tm.getNetworkCountryIso() + "\n");
		sb.append("网络运营商=" + tm.getNetworkOperator() + "\n");
		sb.append("运营商名称=" + tm.getNetworkOperatorName() + "\n");
		sb.append("网络类型=" + tm.getNetworkType() + "\n");
		sb.append("手机类型=" + tm.getPhoneType() + "\n");
		sb.append("imsi=" + tm.getSubscriberId() + "\n");
		sb.append("数据状态=" + tm.getDataState() + "\n");

		// case TelephonyManager.SIM_STATE_ABSENT :sb.append("无卡");break;
		// case TelephonyManager.SIM_STATE_UNKNOWN :sb.append("未知状态");break;
		// case TelephonyManager.SIM_STATE_NETWORK_LOCKED
		// :sb.append("需要NetworkPIN解锁");break;
		// case TelephonyManager.SIM_STATE_PIN_REQUIRED
		// :sb.append("需要PIN解锁");break;
		// case TelephonyManager.SIM_STATE_PUK_REQUIRED
		// :sb.append("需要PUK解锁");break;
		// case TelephonyManager.SIM_STATE_READY :sb.append("良好");break;

		sb.append("sim卡国家iso=" + tm.getSimCountryIso() + "\n");
		sb.append("sim卡运营商=" + tm.getSimOperator() + "\n");
		sb.append("sim卡运营商名称=" + tm.getSimOperatorName() + "\n");
		sb.append("sim卡状态=" + tm.getSimState() + "\n");
		sb.append("ICCID sim串号=" + tm.getSimSerialNumber() + "\n");

		sb.append("========Build类============" + "\n");

		sb.append("Build.BOARD:处理器 " + Build.BOARD + "\n");
		sb.append("Build.MODEL:手机设备版本" + Build.MODEL + "\n");
		sb.append("Build.MANUFACTURER: " + Build.MANUFACTURER + "\n");
		sb.append("Build.PRODUCT:设备正式名称 " + Build.PRODUCT + "\n");
		sb.append("Build.USER:用户名" + Build.USER + "\n");

		sb.append("Build.ID: " + Build.ID + "\n");
		sb.append("Build.DEVICE:硬件设备 " + Build.DEVICE + "\n");
		sb.append("Build.DEVICE:手机平台版本 " + Build.DISPLAY + "\n");
		sb.append("Build.SERIAL: " + Build.SERIAL + "\n");
		sb.append("Build.BRAND:设备品牌 " + Build.BRAND + "\n");
		sb.append("cpu版本 " + Build.CPU_ABI + "\n");
		sb.append("cpu版本2 " + Build.CPU_ABI2 + "\n");

		sb.append("手机android SDK版本号: " + Build.VERSION.SDK_INT + "\n");
		sb.append("手机android版本号RELEASE: " + Build.VERSION.RELEASE + "\n");

		sb.append("========Secure类============" + "\n");
		sb.append("Secure.ANDROID_ID: " + android_id + "\n");

		sb.append("========Locale类============" + "\n");
		sb.append("手机语言: " + Locale.getDefault().getLanguage() + "\n");

		sb.append("========自定义函数============" + "\n");

		sb.append("MAC地址: " + getMacAddress(context) + "\n");
		sb.append("wifi IP地址: " + getlocalip(context) + "\n");
		sb.append("wifi 状态: " + getWifiState(context) + "\n");

		sb.append("手机的宽高: " + getWeithAndHeight(context) + "\n");

		sb.append("屏幕密度: " + getDensity(context) + "\n");
		sb.append("屏幕密度Dpi: " + getDensityDpi(context) + "\n");

		return sb.toString();
	}

	/**
	 * 获取手机屏幕高度--像素
	 */
	private static String getWeithAndHeight(Context context) {
		// 这种方式在service中无法使用，
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager(context).getDefaultDisplay().getMetrics(dm);
		String width_height = "宽" + dm.widthPixels + "高" + dm.heightPixels;

		// //在service中也能得到高和宽
		// WindowManager mWindowManager = (WindowManager)
		// getSystemService(Context.WINDOW_SERVICE);
		// width = mWindowManager.getDefaultDisplay().getWidth();
		// height = mWindowManager.getDefaultDisplay().getHeight();

		return width_height;

	}

	/**
	 * 获取网络的时时网速，使用方法是： 每隔一段时间读取一次总流量，然后用本次和前一次的差除以间隔时间来获取平均速度，再换算为 K/s M/s
	 * 等单位，显示即可。
	 * 
	 * @return 实时的网速（单位byte）
	 */
	public static int getNetSpeedBytes() {
		String line;
		String[] segs;
		int received = 0;
		int i;
		int tmp = 0;
		boolean isNum;
		try {
			FileReader fr = new FileReader("/proc/net/dev");
			BufferedReader in = new BufferedReader(fr, 500);
			while ((line = in.readLine()) != null) {
				line = line.trim();
				if (line.startsWith("rmnet") || line.startsWith("eth") || line.startsWith("wlan")) {
					segs = line.split(":")[1].split(" ");
					for (i = 0; i < segs.length; i++) {
						isNum = true;
						try {
							tmp = Integer.parseInt(segs[i]);
						} catch (Exception e) {
							isNum = false;
						}
						if (isNum == true) {
							received = received + tmp;
							break;
						}
					}
				}
			}
			in.close();
		} catch (IOException e) {
			return -1;
		}
		return received;
	}

	/**
	 * 获取手机屏幕密度 0.75/1.0/1.5
	 */
	private static float getDensity(Context context) {
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager(context).getDefaultDisplay().getMetrics(dm);
		return dm.density;
	}

	/**
	 * 获取手机屏幕密度 0.75/1.0/1.5
	 */
	private static int getDensityDpi(Context context) {
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager(context).getDefaultDisplay().getMetrics(dm);
		return dm.densityDpi;
	}

	private static WindowManager getWindowManager(Context context) {
		// TODO Auto-generated method stub
		WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		return windowManager;
	}

	/**
	 * 获取手机MAC地址
	 * 
	 * @return
	 */
	private static String getMacAddress(Context context) {

		// 在wifi未开启状态下，仍然可以获取MAC地址，但是IP地址必须在已连接状态下否则为0
		String s_macAddress = "";
		WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = (null == wifiMgr ? null : wifiMgr.getConnectionInfo());
		if (null != info) {
			s_macAddress = info.getMacAddress();
		}

		return s_macAddress;
	}

	private static int getWifiState(Context context) {
		WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		if (wifiManager != null) {

			int wifiState = wifiManager.getWifiState();
			return wifiState;

		}
		return wifiManager.WIFI_STATE_UNKNOWN;

	}

	/**
	 * 察看WIFI的IP地址的方法
	 * 
	 * @return
	 */
	private static String getlocalip(Context context) {
		WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		int ipAddress = wifiInfo.getIpAddress();

		if (ipAddress == 0)
			return null;
		return ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "." + (ipAddress >> 16 & 0xff) + "."
				+ (ipAddress >> 24 & 0xff));
	}

	/**
	 * 获取所有安装的应用程序
	 * 
	 * @param context
	 * @return
	 */
	public static List<String> getAllApp(Context context) {
		List<String> appInfos = new ArrayList<>();
		List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(0);
		for (PackageInfo i : packages) {
			if ((i.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
				// result +=
				// i.applicationInfo.loadLabel(context.getPackageManager()).toString()
				// + ",";
				appInfos.add(i.applicationInfo.loadLabel(context.getPackageManager()).toString());

			}
		}
		return appInfos;
	}

}
