封装了安装常用的设备信息查询的工具类:
设备宽度、设备高度、SD卡判断、是否有网、版本名称、版本号、唯一标识、手机品牌、手机型号、API等级、Android版本、App进程Id、App进程Name、Meta-Data值、内网ip、公网ip(请求淘宝接口);
package com.xxx.util;
import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
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.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.util.Log;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
/**
* 设备信息的工具类
*
* Created by Beluga_白鲸.
*/
public class DeviceUtil {
/**
* 获取设备宽度(px)
*
* @param context
* @return
*/
public static int deviceWidth(Context context) {
return context.getResources().getDisplayMetrics().widthPixels;
}
/**
* 获取设备高度(px)
*
* @param context
* @return
*/
public static int deviceHeight(Context context) {
return context.getResources().getDisplayMetrics().heightPixels;
}
/**
* SD卡判断
*
* @return
*/
public static boolean isSDCardAvailable() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
/**
* 是否有网
*
* @param context
* @return
*/
public static boolean isNetworkConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkInfo != null) {
return mNetworkInfo.isAvailable();
}
}
return false;
}
/**
* 返回版本名字
* 对应build.gradle中的versionName
*
* @param context
* @return
*/
public static String getVersionName(Context context) {
String versionName = "";
try {
PackageManager packageManager = context.getPackageManager();
PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
versionName = packInfo.versionName;
} catch (Exception e) {
e.printStackTrace();
}
return versionName;
}
/**
* 返回版本号
* 对应build.gradle中的versionCode
*
* @param context
* @return
*/
public static String getVersionCode(Context context) {
String versionCode = "";
try {
PackageManager packageManager = context.getPackageManager();
PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
versionCode = String.valueOf(packInfo.versionCode);
} catch (Exception e) {
e.printStackTrace();
}
return versionCode;
}
/**
* 获取设备的唯一标识,deviceId
*
* @param context
* @return
*/
public static String getDeviceId(Context context) {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
//没有权限则返回""
return "";
} else {
String deviceId = tm.getDeviceId();
if (deviceId == null) {
return "";
} else {
return deviceId;
}
}
}
/**
* 获取手机品牌
*
* @return
*/
public static String getPhoneBrand() {
return android.os.Build.BRAND;
}
/**
* 获取手机型号
*
* @return
*/
public static String getPhoneModel() {
return android.os.Build.MODEL;
}
/**
* 获取手机Android API等级(22、23 ...)
*
* @return
*/
public static int getBuildLevel() {
return android.os.Build.VERSION.SDK_INT;
}
/**
* 获取手机Android 版本(4.4、5.0、5.1 ...)
*
* @return
*/
public static String getBuildVersion() {
return android.os.Build.VERSION.RELEASE;
}
/**
* 获取当前App进程的id
*
* @return
*/
public static int getAppProcessId() {
return android.os.Process.myPid();
}
/**
* 获取当前App进程的Name
*
* @param context
* @param processId
* @return
*/
public static String getAppProcessName(Context context, int processId) {
String processName = null;
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
// 获取所有运行App的进程集合
List l = am.getRunningAppProcesses();
Iterator i = l.iterator();
PackageManager pm = context.getPackageManager();
while (i.hasNext()) {
ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
try {
if (info.pid == processId) {
CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
processName = info.processName;
return processName;
}
} catch (Exception e) {
Log.e(DeviceUtil.class.getName(), e.getMessage(), e);
}
}
return processName;
}
/**
* 创建App文件夹
*
* @param appName
* @param application
* @return
*/
public static String createAPPFolder(String appName, Application application) {
return createAPPFolder(appName, application, null);
}
/**
* 创建App文件夹
*
* @param appName
* @param application
* @param folderName
* @return
*/
public static String createAPPFolder(String appName, Application application, String folderName) {
File root = Environment.getExternalStorageDirectory();
File folder;
/**
* 如果存在SD卡
*/
if (DeviceUtil.isSDCardAvailable() && root != null) {
folder = new File(root, appName);
if (!folder.exists()) {
folder.mkdirs();
}
} else {
/**
* 不存在SD卡,就放到缓存文件夹内
*/
root = application.getCacheDir();
folder = new File(root, appName);
if (!folder.exists()) {
folder.mkdirs();
}
}
if (folderName != null) {
folder = new File(folder, folderName);
if (!folder.exists()) {
folder.mkdirs();
}
}
return folder.getAbsolutePath();
}
/**
* 通过Uri找到File
*
* @param context
* @param uri
* @return
*/
public static File uri2File(Activity context, Uri uri) {
File file;
String[] project = {MediaStore.Images.Media.DATA};
Cursor actualImageCursor = context.getContentResolver().query(uri, project, null, null, null);
if (actualImageCursor != null) {
int actual_image_column_index = actualImageCursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualImageCursor.moveToFirst();
String img_path = actualImageCursor
.getString(actual_image_column_index);
file = new File(img_path);
} else {
file = new File(uri.getPath());
}
if (actualImageCursor != null) actualImageCursor.close();
return file;
}
/**
* 获取AndroidManifest.xml里 的值
*
* @param context
* @param name
* @return
*/
public static String getMetaData(Context context, String name) {
String value = null;
try {
ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
value = appInfo.metaData.getString(name);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return value;
}
/**
* 判断当前设备是手机还是平板,代码来自 Google I/O App for Android
*
* @param context
* @return 平板返回 True,手机返回 False
*/
public static boolean isPad(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
/**
* 获取ip(内网ip)
* @param context
* @return
*/
public static String getIPAddress(Context context) {
NetworkInfo info = ((ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info != null && info.isConnected()) {
if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
try {
//Enumeration en=NetworkInterface.getNetworkInterfaces();
for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
} else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
return ipAddress;
}
} else {
//当前无网络连接,请在设置中打开网络
}
return null;
}
/**
* 将得到的int类型的IP转换为String类型
*
* @param ip
* @return
*/
public static String intIP2StringIP(int ip) {
return (ip & 0xFF) + "." +
((ip >> 8) & 0xFF) + "." +
((ip >> 16) & 0xFF) + "." +
(ip >> 24 & 0xFF);
}
/**
* 获取IP(外网ip、公网ip)
*/
public static String getNetIp() {
String IP = "";
try {
String address = "http://ip.taobao.com/service/getIpInfo2.php?ip=myip";
URL url = new URL(address);
//URLConnection htpurl=url.openConnection();
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setUseCaches(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("user-agent",
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.7 Safari/537.36"); //设置浏览器ua 保证不出现503
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream in = connection.getInputStream();
// 将流转化为字符串
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
String tmpString = "";
StringBuilder retJSON = new StringBuilder();
while ((tmpString = reader.readLine()) != null) {
retJSON.append(tmpString + "\n");
}
JSONObject jsonObject = new JSONObject(retJSON.toString());
String code = jsonObject.getString("code");
if (code.equals("0")) {
JSONObject data = jsonObject.getJSONObject("data");
//格式:180.000.00.000(中国区上海上海电信)
// IP = data.getString("ip") + "(" + data.getString("country")
// + data.getString("area") + "区"
// + data.getString("region") + data.getString("city")
// + data.getString("isp") + ")";
//格式:180.000.00.000
IP = data.getString("ip");
Log.e("提示", "您的IP地址是:" + IP);
} else {
IP = "";
Log.e("提示", "IP接口异常,无法获取IP地址!");
}
} else {
IP = "";
Log.e("提示", "网络连接异常,无法获取IP地址!");
}
} catch (Exception e) {
IP = "";
Log.e("提示", "获取IP地址时出现异常,异常信息是:" + e.toString());
}
return IP;
}
public static String streamreader(InputStream is) throws IOException {
//转换为字符
InputStreamReader isr = new InputStreamReader(is, "gbk");
BufferedReader br = new BufferedReader(isr);
StringBuilder stringBuilder=new StringBuilder();
for(String tmp = br.readLine();tmp!= null;tmp = br.readLine()){
stringBuilder.append(tmp);
}
return stringBuilder.toString();
}
}