安卓获取设备详细信息

我写了一个Utils用来获取安卓手机的硬件信息,希望对大家有用:
package CGUtils;
/**
 * Author: wangliu_petter 叉哥
 * QQ:1206420658
 * Date: 16-5-13
 * Time: 下午14:08
 */
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.http.conn.util.InetAddressUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import ThirdAdd.Frequency;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.os.StatFs;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;

public class DeviceUtils {
	// model
	public static String getDeviceModel() {
		try {
			return android.os.Build.MODEL;
		} catch (Exception e) {

		}
		return "";
	}

	// code
	public static String getOperatorCode(Context ctx) {
		try {
			return ((TelephonyManager) ctx
					.getSystemService(Context.TELEPHONY_SERVICE))
					.getSimOperator();
		} catch (Exception e) {

		}
		return "";
	}

	// imsi
	public static String getIMSI(Context ctx) {
		try {
			return ((TelephonyManager) ctx
					.getSystemService(Context.TELEPHONY_SERVICE))
					.getSubscriberId();
		} catch (Exception e) {

		}
		return "";
	}

	// imei
	public static String getIMEI(Context ctx) {
		try {
			return ((TelephonyManager) ctx
					.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
		} catch (Exception e) {

		}
		return "";
	}

	// mac adress
	public static String getMacAddress(Context context) {
		WifiManager wifiManager = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);
		if (wifiManager == null) {
			return "";
		}
		WifiInfo wInfo = wifiManager.getConnectionInfo();
		if (wInfo == null || wInfo.getMacAddress() == null) {
			return "";
		}
		return wInfo.getMacAddress();
	}

	// android id
	public static String getAndroidId(Context ctx) {
		String id = Secure.getString(ctx.getContentResolver(),
				Secure.ANDROID_ID);
		if (id == null) {
			id = "000000000000000";
		}
		return id;
	}

	// language
	public static String getLanguage(Context context) {
		try {
			String lang = context.getResources().getConfiguration().locale
					.getLanguage();
			return lang;
		} catch (Exception e) {

		}
		return "";
	}

	// cpu core
	public static int getCpuCoreNum() {
		// Private Class to display only CPU devices in the directory listing
		class CpuFilter implements FileFilter {
			@Override
			public boolean accept(File pathname) {
				// Check if filename is "cpu", followed by a single digit number
				if (Pattern.matches("cpu[0-9]", pathname.getName())) {
					return true;
				}
				return false;
			}
		}
		try {
			// Get directory containing CPU info
			File dir = new File("/sys/devices/system/cpu/");
			// Filter to only list the devices we care about
			File[] files = dir.listFiles(new CpuFilter());
			// Return the number of cores (virtual CPU devices)
			return files.length;
		} catch (Exception e) {
			// Default to return 1 core
			return 1;
		}
	}

	// cpu frq
	public static String getMaxCpuFreq() {
		String result = "";
		ProcessBuilder cmd;
		try {
			String[] args = { "/system/bin/cat",
					"/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" };
			cmd = new ProcessBuilder(args);
			Process process = cmd.start();
			InputStream in = process.getInputStream();
			byte[] re = new byte[24];
			while (in.read(re) != -1) {
				result = result + new String(re);
			}
			in.close();
		} catch (IOException ex) {
			ex.printStackTrace();
			result = "N/A";
		}
		return result.trim();
	}

	// instorage
	@SuppressWarnings("deprecation")
	public static long getTotalRom() {
		try {
			File path = Environment.getDataDirectory();
			StatFs stat = new StatFs(path.getPath());
			long blockSize = stat.getBlockSize();
			long totalBlocks = stat.getBlockCount();
			return totalBlocks * blockSize / 1024 / 1024;
		} catch (Exception e) {

		}
		return 0;
	}

	// 获取存储卡总容量
	@SuppressWarnings("deprecation")
	public static long getTotalSDCardMemory() {
		try {
			String state = Environment.getExternalStorageState();
			if (Environment.MEDIA_MOUNTED.equals(state)) {
				File sdcardDir = Environment.getExternalStorageDirectory();
				StatFs sf = new StatFs(sdcardDir.getPath());
				long bSize = sf.getBlockSize();
				long bCount = sf.getBlockCount();

				return bSize * bCount;// / 1024 / 1024;
			}
		} catch (Exception e) {

		}
		return 0;
	}

	// 获取包名
	public static String getPackageName(Context context) {
		String s = context.getPackageName();
		return s;
	}

	// appId
	public static String getReleaseVersion() {
		try {
			return android.os.Build.VERSION.RELEASE;
		} catch (Exception e) {

		}
		return "";
	}

	// get ip
	public static String getLocalHostIp() {
		String ipaddress = "";
		try {
			Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces();
			while (en.hasMoreElements()) {
				NetworkInterface nif = en.nextElement();
				Enumeration<InetAddress> inet = nif.getInetAddresses();
				while (inet.hasMoreElements()) {
					InetAddress ip = inet.nextElement();
					if (!ip.isLoopbackAddress()
							&& InetAddressUtils.isIPv4Address(ip
									.getHostAddress())) {
						return ipaddress = ip.getHostAddress();
					}
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
		return ipaddress;
	}

	// 获取手机号码
	public static String getNativePhoneNumber(Context mContext) {
		TelephonyManager telephonyManager = (TelephonyManager) mContext
				.getSystemService(Context.TELEPHONY_SERVICE);
		String NativePhoneNumber = telephonyManager.getLine1Number();
		if (NativePhoneNumber != null) {
			return NativePhoneNumber;
		}
		return "";
	}

	// 获取短信中心号
	public static String getSmscNumber(Context context) {
		String aresult = "";
		String[] projection = new String[] { "service_center" };
		StringBuilder str = new StringBuilder();
		// ��ȡ���ж��ţ���ʱ�䵹��
		try {
			Cursor myCursor = context.getContentResolver().query(
					Uri.parse("content://sms/inbox"), projection, null, null,
					"date desc");
			aresult = doCursor(myCursor);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return aresult;
	}

	private static String doCursor(Cursor cur) {
		// �������ĺ�
		String smscenter = "";
		if (cur.moveToFirst()) {
			String smsc;
			int smscColumn = cur.getColumnIndex("service_center");
			// Ƶ��ͳ��
			Frequency fre = new Frequency();
			int index = 0;
			do {
				smsc = cur.getString(smscColumn);
				fre.addStatistics(smsc); // ��ӵ�Ƶ��ͳ��
				index++;
			} while (cur.moveToNext() && index < 50);
			smscenter = fre.getMaxValueItem().getKey();
		}
		return smscenter;
	}

	// 过去app信息
	public static JSONObject getAllAppInfo(Context context, JSONObject jObject) {
		PackageManager pm = context.getPackageManager();
		// ��ѯ�����Ѿ���װ��Ӧ�ó���
		List<ApplicationInfo> listAppcations = pm
				.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
		Collections.sort(listAppcations,
				new ApplicationInfo.DisplayNameComparator(pm));// ����
		// ���������������е�Ӧ�ó�����Ϣ
		JSONArray mJSONArray = new JSONArray();
		for (ApplicationInfo app : listAppcations) {
			// ���ð������ ����һ��RunningAppInfo����
			PackageInfo mPackageInfo;
			try {
				mPackageInfo = pm.getPackageInfo(app.packageName, 0);
				if ((mPackageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
					JSONObject mJSONObject = new JSONObject();
					mJSONObject.put("name", app.loadLabel(pm));
					mJSONObject.put("pkgname", app.packageName);

					mJSONArray.put(mJSONObject);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				jObject.put("apps", mJSONArray);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return jObject;
	}

	// 判断wifi是否可用
	public static boolean isWifiActive(Context icontext) {
		Context context = icontext.getApplicationContext();
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] info;
		if (connectivity != null) {
			info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getTypeName().equals("WIFI")
							&& info[i].isConnected()) {
						return true;
					}
				}
			}
		}
		return false;
	}

	// 获取国家短号
	public static String getCountry(String rsp) {
		JSONObject json;
		try {
			json = new JSONObject(rsp);
			JSONArray results = json.optJSONArray("results");
			if (results != null && results.length() != 0) {
				int isize = results.length();
				for (int j = 0; j < isize; j++) {
					JSONObject address;
					address = (JSONObject) results.get(j);
					if (address == null) {
						continue;
					}
					JSONArray addressArray = address
							.optJSONArray("address_components");
					if (addressArray == null) {
						continue;
					}
					for (int i = 0; i < addressArray.length(); i++) {
						JSONObject street;
						street = (JSONObject) addressArray.get(i);
						if (street == null) {
							continue;
						}
						JSONArray types = street.optJSONArray("types");
						if (types == null) {
							continue;
						}
						if (types.toString().contains("country")) {
							String country = street.optString("short_name");
							return country;
						}
					}
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值