Android 整理一些特别好用的util: HttpUtils、DevicesUtils、NetUtils
平时工作中经常用到的油条:
Http请求:
package com.yc.utils;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
public class HttpUtils {
public static String httpGet(String url, Map<String, String> params) {
List<NameValuePair> lst = new ArrayList<NameValuePair>();
if (params != null) {
Iterator<String> keyItors = params.keySet().iterator();
while (keyItors.hasNext()) {
String key = keyItors.next();
String val = params.get(key);
lst.add(new BasicNameValuePair(key, val));
}
}
return httpGet(url, lst);
}
public static String httpPost(String url, Map<String, String> params) {
List<NameValuePair> lst = new ArrayList<NameValuePair>();
if (params != null) {
Iterator<String> keyItors = params.keySet().iterator();
while (keyItors.hasNext()) {
String key = keyItors.next();
String val = params.get(key);
lst.add(new BasicNameValuePair(key, val));
}
}
return httpPost(url, lst);
}
public static String httpGet(String urlStr, List<NameValuePair> params) {
String fullUrl = urlStr;
if (params != null && params.size() > 0) {
fullUrl = urlStr + "?" + URLEncodedUtils.format(params, "UTF-8");
}
String result = null;
URL url = null;
HttpURLConnection connection = null;
InputStreamReader in = null;
try {
url = new URL(fullUrl);
connection = (HttpURLConnection) url.openConnection();
in = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(in);
StringBuffer strBuffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
strBuffer.append(line);
}
result = strBuffer.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
public static String httpPost(String urlStr, List<NameValuePair> params) {
String paramsEncoded = "";
if (params != null && params.size() > 0) {
paramsEncoded = URLEncodedUtils.format(params, "UTF-8");
}
String result = null;
URL url = null;
HttpURLConnection connection = null;
InputStreamReader in = null;
try {
url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Charset", "utf-8");
DataOutputStream dop = new DataOutputStream(
connection.getOutputStream());
dop.writeBytes(paramsEncoded);
dop.flush();
dop.close();
in = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(in);
StringBuffer strBuffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
strBuffer.append(line);
}
result = strBuffer.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
}
获取设备信息:
package com.yc.utils;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.webkit.WebView;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;
public class DeviceUtil {
public static final String ERROR_MAC_STR = "02:00:00:00:00:00";//安卓6.0以上版本获取mac失败时返回值
public static final String DEVICE_INFO_NAME = "deviceInfo";
public static final String LOCAL_SAVE_UUID = "local_uuid";
public static final String DEVICE_FILE_NAME = "dxsavedeviceinfo";
public static String getPhoneNum(Context context) {
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
String phoneNum = null;
try {
phoneNum = telephonyManager.getLine1Number();
} catch (Exception e) {
e.printStackTrace();
}
if (TextUtils.isEmpty(phoneNum)) {
return "null";
} else {
return phoneNum;
}
}
/**
* 获取SIM卡运营商
*
* @param context
* @return
*/
public static String getOperators(Context context) {
TelephonyManager tm = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
String operator = null;
String IMSI = null;
try {
IMSI = tm.getSubscriberId();
} catch (Exception e) {
e.printStackTrace();
}
if (IMSI == null || IMSI.equals("")) {
return operator;
}
if (IMSI.startsWith("46000") || IMSI.startsWith("46002")) {
operator = "中国移动";
} else if (IMSI.startsWith("46001")) {
operator = "中国联通";
} else if (IMSI.startsWith("46003")) {
operator = "中国电信";
}
if (TextUtils.isEmpty(operator)) {
return "null";
} else {
return operator;
}
}
/**
* 手机型号
*
* @return
*/
public static String getPhoneModel() {
if (TextUtils.isEmpty(Build.MODEL)) {
return "null";
} else {
return Build.MODEL;
}
}
/**
* 获取ua信息
*
* @throws UnsupportedEncodingException
*/
public static String getUserUa(Context context) {
WebView webview = new WebView(context);
webview.layout(0, 0, 0, 0);
String str = webview.getSettings().getUserAgentString();
return str;
}
/**
* 获取ip地址
*
* @return
*/
public static String getHostIP() {
String hostIp = null;
try {
Enumeration nis = NetworkInterface.getNetworkInterfaces();
InetAddress ia = null;
while (nis.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) nis.nextElement();
Enumeration<InetAddress> ias = ni.getInetAddresses();
while (ias.hasMoreElements()) {
ia = ias.nextElement();
if (ia instanceof Inet6Address) {
continue;// skip ipv6
}
String ip = ia.getHostAddress();
if (!"127.0.0.1".equals(ip)) {
hostIp = ia.getHostAddress();
break;
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return hostIp;
}
private static boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(str).matches();
}
// 获取imei或者meid(android4.0之前)
private static Map getImeiOrMeid(Context context) {
Map<String, String> map = new HashMap<>();
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try {
String deviceId = tm.getDeviceId();
if (!TextUtils.isEmpty(deviceId)) {
if (isNumeric(deviceId)) {
map.put("imei1", deviceId);
} else {
map.put("meid", deviceId);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
// 获取imei和meid(android5.0)
@TargetApi(Build.VERSION_CODES.M)
private static Map getImeiAndMeid(Context ctx) {
Map<String, String> map = new HashMap<>();
TelephonyManager mTelephonyManager = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
Class<?> clazz = null;
Method method = null;//(int slotId)
try {
clazz = Class.forName("android.os.SystemProperties");
method = clazz.getMethod("get", String.class, String.class);
String gsm = (String) method.invoke(null, "ril.gsm.imei", "");
String meid = (String) method.invoke(null, "ril.cdma.meid", "");
map.put("meid", meid);
if (!TextUtils.isEmpty(gsm)) {
//the value of gsm like:xxxxxx,xxxxxx
String imeiArray[] = gsm.split(",");
if (imeiArray != null && imeiArray.length > 0) {
map.put("imei1", imeiArray[0]);
if (imeiArray.length > 1) {
map.put("imei2", imeiArray[1]);
} else {
map.put("imei2", mTelephonyManager.getDeviceId(1));
}
} else {
map.put("imei1", mTelephonyManager.getDeviceId(0));
map.put("imei2", mTelephonyManager.getDeviceId(1));
}
} else {
map.put("imei1", mTelephonyManager.getDeviceId(0));
map.put("imei2", mTelephonyManager.getDeviceId(1));
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
//获取imei和meid(android6.0以后)
@TargetApi(Build.VERSION_CODES.O)
private static Map getIMEIStatus(Context context) {
Map<String, String> map = new HashMap<String, String>();
TelephonyManager tm = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE));
try {
map.put("imei1", tm.getImei(0));
map.put("imei2", tm.getImei(1));
map.put("meid", tm.getMeid()); //如果CDMA制式手机返回MEID
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
private static String checkImeiOrMeid(Map imeiMaps) {
if (imeiMaps != null) {
String imei1 = (String) imeiMaps.get("imei1");
if (!TextUtils.isEmpty(imei1)) {
return "IMEI_" + imei1;
}
String imei2 = (String) imeiMaps.get("imei2");
if (!TextUtils.isEmpty(imei2)) {
return "IMEI_" + imei2;
}
String meid = (String) imeiMaps.get("meid");
if (!TextUtils.isEmpty(meid)) {
return "MEID_" + meid;
}
}
return "";
}
public static String getIMEI(Context ctx) {
Map imeiMaps;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { //4.0以下 直接获取
imeiMaps = getImeiOrMeid(ctx);
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { //5.0,6.0系统
imeiMaps = getImeiAndMeid(ctx);
} else {
imeiMaps = getIMEIStatus(ctx);
}
String imei = checkImeiOrMeid(imeiMaps);
return imei;
}
// Mac地址(android6.0以前版本)
private static String getLocalMac(Context context) {
String mac = ERROR_MAC_STR;
WifiManager wifi = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
try {
WifiInfo info = wifi.getConnectionInfo();
mac = info.getMacAddress();
} catch (Exception e) {
e.printStackTrace();
}
return mac;
}
// Mac地址 (Android 6.0包括 - Android 7.0不包括)
private static String getMacFromFile() {
String WifiAddress = ERROR_MAC_STR;
try {
WifiAddress = new BufferedReader(new FileReader(new File("/sys/class/net/wlan0/address"))).readLine();
} catch (IOException e) {
e.printStackTrace();
}
return WifiAddress;
}
/**
* 遍历循环所有的网络接口,找到接口是 wlan0
* 必须的权限 <uses-permission android:name="android.permission.INTERNET" />
*/
private static String getMacFromHardware() {
try {
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return "";
}
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
res1.append(String.format("%02X:", b));
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return ERROR_MAC_STR;
}
/**
* 获取mac地址
*
* @param context
* @return
*/
public static String getMacAddress(Context context) {
String mac = "";
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
mac = getLocalMac(context);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
mac = getMacFromFile();
} else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
mac = getMacFromHardware();
}
if (mac.equals(ERROR_MAC_STR)) {
mac = "";
}
if (!TextUtils.isEmpty(mac)) {
return "MAC_" + mac.replace(":", "");
}
return mac;
}
/**
* Pseudo-Unique ID, 这个在任何Android手机中都有效
* 有一些特殊的情况,一些如平板电脑的设置没有通话功能,或者你不愿加入READ_PHONE_STATE许可。而你仍然想获得唯
* 一序列号之类的东西。这时你可以通过取出ROM版本、制造商、CPU型号、以及其他硬件信息来实现这一点。这样计算出
* 来的ID不是唯一的(因为如果两个手机应用了同样的硬件以及Rom 镜像)。但应当明白的是,出现类似情况的可能性基
* 本可以忽略。大多数的Build成员都是字符串形式的,我们只取他们的长度信息。我们取到13个数字,并在前面加上“35
* ”。这样这个ID看起来就和15位IMEI一样了。
*/
public static String getPesudoUniqueID() {
String m_szDevIDShort = "35" + //we make this look like a valid IMEI
Build.BOARD.length() % 10 +
Build.BRAND.length() % 10 +
Build.CPU_ABI.length() % 10 +
Build.DEVICE.length() % 10 +
Build.DISPLAY.length() % 10 +
Build.HOST.length() % 10 +
Build.ID.length() % 10 +
Build.MANUFACTURER.length() % 10 +
Build.MODEL.length() % 10 +
Build.PRODUCT.length() % 10 +
Build.TAGS.length() % 10 +
Build.TYPE.length() % 10 +
Build.USER.length() % 10; //13 digits
return m_szDevIDShort;
}
//获取uuid
public static String getLocalUUID() {
String uuid = "";
String fileData = getLocalDeviceInfo();
try {
if (TextUtils.isEmpty(fileData)) {
uuid = UUID.randomUUID().toString();
JSONObject jsonObject = new JSONObject();
jsonObject.putOpt(LOCAL_SAVE_UUID, uuid);
saveLocalDeviceInfo(jsonObject.toString());
} else {
JSONObject jsonObject = new JSONObject(fileData);
uuid = jsonObject.optString(LOCAL_SAVE_UUID);
if (TextUtils.isEmpty(uuid)) {
uuid = UUID.randomUUID().toString();
jsonObject.putOpt(LOCAL_SAVE_UUID, uuid);
saveLocalDeviceInfo(jsonObject.toString());
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return uuid;
}
private static String getLocalFilePath() {
String filePath = null;
boolean hasSDCard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
if (hasSDCard) { // SD卡根目录
filePath = Environment.getExternalStorageDirectory().toString() + File.separator + DEVICE_INFO_NAME + File.separator + DEVICE_FILE_NAME;
} else { // 系统下载缓存根目录
filePath = Environment.getDownloadCacheDirectory().toString() + File.separator + DEVICE_INFO_NAME + File.separator + DEVICE_FILE_NAME;
}
return filePath;
}
private static String getLocalDeviceInfo() {
StringBuilder sb = new StringBuilder();
String filePath = getLocalFilePath();
File file = new File(filePath);
try {
if (!file.exists()) {
File dir = new File(file.getParent());
dir.mkdirs();
file.createNewFile();
}
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
sb.append(new String(buffer, 0, len));
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
private static void saveLocalDeviceInfo(String info) {
if (TextUtils.isEmpty(info)) {
return;
}
String filePath = getLocalFilePath();
File file = new File(filePath);
try {
if (!file.exists()) {
File dir = new File(file.getParent());
dir.mkdirs();
file.createNewFile();
}
FileOutputStream outStream = new FileOutputStream(file);
outStream.write(info.getBytes("utf-8"));
outStream.flush();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Android Id
private static String getAndroidId(Context context) {
String androidId = Settings.Secure.getString(
context.getContentResolver(), Settings.Secure.ANDROID_ID);
return androidId;
}
public static boolean isPhone(Context context) {
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
int type = telephony.getPhoneType();
if (type == 0) {
return false;
} else {
return true;
}
}
/**
* 获取设备ID
*
* @param context
* @return
*/
public static String getDeviceId(Context context) {
String deviceId = "";
// if(isPhone(context)) {//是通信设备使用设备id
deviceId = getIMEI(context);
// } else {//使用android_id
// deviceId = getAndroidId(context);
// }
if (!TextUtils.isEmpty(deviceId)) {
return deviceId;
}
//使用mac地址
deviceId = getMacAddress(context);
if (!TextUtils.isEmpty(deviceId)) {
return deviceId;
}
//使用Pseudo-Unique ID
// deviceId = getPesudoUniqueID();
// if(!TextUtils.isEmpty(deviceId)){
// return "PUID_" + deviceId;
// }
//使用UUID
deviceId = "UUID_" + getLocalUUID().replace("-", "");
return deviceId;
}
/**
* 获取当前应用程序的版本号
*
* @return
* @author wangjie
*/
public static int getAppVersionCode(Context context) {
int version = 1;
try {
version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return version;
}
/**
* 判断是魅族操作系统
*
* @return true 为魅族系统 否则不是
*/
public static boolean isMeizuFlymeOS() {
/* 获取魅族系统操作版本标识*/
String meizuFlymeOSFlag = getSystemProperty("ro.build.display.id", "");
if (TextUtils.isEmpty(meizuFlymeOSFlag)) {
return false;
} else if (meizuFlymeOSFlag.contains("flyme") || meizuFlymeOSFlag.contains("flyme")) {
return true;
} else {
return false;
}
}
/**
* 获取系统属性
*
* @param key ro.build.display.id
* @param defaultValue 默认值
* @return 系统操作版本标识
*/
private static String getSystemProperty(String key, String defaultValue) {
try {
Class<?> clz = Class.forName("android.os.SystemProperties");
Method get = clz.getMethod("get", String.class, String.class);
return (String) get.invoke(clz, key, defaultValue);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static int isInstallApplication(Context context, String packageName) {
final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
if (pinfo == null || pinfo.size() == 0) {//防止部分手机获取不到应用程序列表时提示未安装
return -1;
}
if (pinfo != null) {
for (int i = 0; i < pinfo.size(); i++) {
String pn = pinfo.get(i).packageName;
if (pn.equals(packageName)) {
return 1;
}
}
}
return 0;
}
}
获取手机网络状态:
package com.yc.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
/***
* 判断网络是否连接
* @author Administrator
*
*/
public class NetUtils {
public static boolean checkNetworkInfo(Context context) {
ConnectivityManager conMan = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
@SuppressWarnings("deprecation")
NetworkInfo mobileInfo = conMan
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
@SuppressWarnings("deprecation")
NetworkInfo wifiInfo = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mobileInfo == null) {
State wifiState = wifiInfo.getState();
if (wifiState == State.CONNECTED || wifiState == State.CONNECTING) {
return true;
} else {
return false;
}
}
State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
.getState();
State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.getState();
if ((mobile == State.CONNECTED || mobile == State.CONNECTING
|| wifi == State.CONNECTED || wifi == State.CONNECTING)) {
return true;
} else {
return false;
}
}
/**
* 检查当前网络是否可用
*
* @param context
* @return
*/
@SuppressWarnings("deprecation")
public static boolean isNetworkAvailable(Context activity) {
//得到应用上下文
Context context = activity.getApplicationContext();
// 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理) notificationManager /alarmManager
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null) {
return false;
} else {
// 获取NetworkInfo对象
NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
if (networkInfo != null && networkInfo.length > 0) {
for (int i = 0; i < networkInfo.length; i++) {
// 判断当前网络状态是否为连接状态
if (networkInfo[i].getState() == State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}
另外分享大神整理的工具类:
Android快速开发系列 10个常用工具类
转 http://blog.youkuaiyun.com/lmj623565791/article/details/38965311 --【张鸿洋的博客】