随着这些年工作的不断积累,开发了各式各样的APP,写了不少功能,后来才慢慢发现很多都有通用型工具,一通百通~
基友篇
此篇涵盖了我从业近5年来所使用的90%的工具方法,包含了时间日期、网络状态、设备信息、应用信息、加密、颜色、图片处理、类型转换、dp-xp转换等多方面的工具方法,希望对大家有所帮助 ~
工具目录总览
日期时间工具
获取当前时间戳
public static String getCurrentTimeMillis() {
return String.format(String.valueOf(System.currentTimeMillis()));
}
获取精确到秒的时间戳
方法一:通过String.substring()方法将最后的三位去掉
/**
* 获取精确到秒的时间戳
* @return
*/
public static int getSecondTimestamp(Date date){
if (null == date) {
return 0;
}
String timestamp = String.valueOf(date.getTime());
int length = timestamp.length();
if (length > 3) {
return Integer.valueOf(timestamp.substring(0,length-3));
} else {
return 0;
}
}
方法二:通过整除将最后的三位去掉
/**
* 获取精确到秒的时间戳
* @param date
* @return
*/
public static int getSecondTimestampTwo(Date date){
if (null == date) {
return 0;
}
String timestamp = String.valueOf(date.getTime()/1000);
return Integer.valueOf(timestamp);
}
获取对应日期的时间戳
private static long getTimeMills(int year,int month,int day,int hour,int minute,int second) {
// TODO Auto-generated method stub
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(year,month,day,hour,minute,second);
Long timeMills = calendar.getTimeInMillis();
return timeMills;
}
获取当前日期
/**
* 获取当前日期--(格式2017-12-06)
*/
public static String getCurrentTime() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return df.format(Calendar.getInstance().getTime());
}
时间戳转为日期字符串 Tyep One~
/**
*返回格式 :2018-01-01 01:00 年月日时分
*/
public static String getStrTime(String timeStamp){
String timeString = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm");
long l = Long.valueOf(timeStamp);
timeString = sdf.format(new Date(l));//单位秒
return timeString;
}
时间戳转为日期字符串 Tyep Two~
/**
* 毫秒转换为的时间
* */
public static String getFormatDateTime(String pattern, long dateTime) {
SimpleDateFormat sDateFormat = new SimpleDateFormat(pattern);
return sDateFormat.format(new Date(dateTime + 0));
}
使用方式:
/**参数1:期望返回日期格式
参数2:时间戳*/
getFormatDateTime("yyyy-MM-dd", longTime);
日期字符串转为时间戳 (如 2018-11-13)
public static String getTime(String timeString){
String timeStamp = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm");
Date d;
try{
d = sdf.parse(timeString);
long l = d.getTime();
timeStamp = String.valueOf(l);
} catch(ParseException e){
e.printStackTrace();
}
return timeStamp;
}
过去一天、七天、一月,且任意时间均可
/**
* 间隔天数已格式化(今天之前)
* @param timeString 输入的时间(格式:2017-12-12),可使用上面的getCurrentTime()获取当前时间,传入参数一 !!!
* @param wantDay 期望过去的天数
*
* 要点:
* 这里有一个概念假若我要过去7天的时间,那么是包含今天?还是不包含今天?
* 假若今天为2018-10-18 当我用此方法输入期望天数7以后得出的数据为2018-10-11(所以工具默认是不包含当天的!)
* 所以如希望包含今天,需要 将期望的wantDay -1 ;如希望获取过去七天数据,直接输入wantDay = 6 既可
*/
public static String getWantIncreaseTime(String timeString, int wantDay) {
String timeStamp = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d;
try {
d = sdf.parse(timeString);
//输入的时间加上1天的时间戳
long l = d.getTime() - (60 * 60 * 24 * wantDay * 1000);
//单位秒
timeStamp = sdf.format(new Date(l));
} catch (ParseException e) {
e.printStackTrace();
}
return timeStamp;
}
过去的任意月数
//动态设置月份数据,如 monthNum传入1,则是过去一个月的时间
public String getDate(int monthNum){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.MONTH, -monthNum);
Date m = c.getTime();
String date= format.format(m);
return date;
}
- 过去30天(因每个月的天数不同,有时候会统一设置为30天处理)
public String getDate(){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, -29);
Date d = c.getTime();
String date = format.format(d);
return date;
}
过去一年
//动态设置年的数据,如 yearNum传入1,则是过去一年的时间
public String getDate(int yearNum){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.YEAR, -yearNum);
Date y = c.getTime();
String year = format.format(y);
return year ;
}
以下时间工具强烈推荐,是我在做经营报表统计年、月、周数据时用到的!非常方便~
- 获取每个自然周的第一天 (直接可用,不是国外以周日作为周一的~此工具内部已经做了处理)
/**
* start
* 本周开始时间戳 - 以星期一为本周的第一天
*/
public static String getWeekStartTime() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
Calendar cal = Calendar.getInstance();
int day_of_week = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (day_of_week == 0) {
day_of_week = 7;
}
cal.add(Calendar.DATE, -day_of_week + 1);
// return simpleDateFormat.format(cal.getTime()) + "000000000";
return simpleDateFormat.format(cal.getTime());
}
获取每个自然周的最后一天
/**
* end
* 本周结束时间戳 - 以星期一为本周的第一天
*/
public static String getWeekEndTime() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
Calendar cal = Calendar.getInstance();
int day_of_week = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (day_of_week == 0) {
day_of_week = 7;
}
cal.add(Calendar.DATE, -day_of_week + 7);
// return simpleDateFormat.format(cal.getTime()) + "235959999";
return simpleDateFormat.format(cal.getTime());
}
获取一周内的所有日期 (不过返回的都是时间戳,需要我们自己通过上面的时间戳转换工具自行转换)
/**
* 获取一周内的所有日期
*/
public static List<Long> getWeekDayList(String date, String formatSrt) {
// 存放每一天时间的集合
List<Long> weekMillisList = new ArrayList<Long>();
long dateMill = 0;
try {
// 获取date的毫秒值
dateMill = getMillis(date, formatSrt);
} catch (ParseException e) {
e.printStackTrace();
}
// Calendar
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(dateMill);
// 本周的第几天
int weekNumber = calendar.get(Calendar.DAY_OF_WEEK);
TlogUtils.e("本周第几天", weekNumber + "");
// 获取本周一的毫秒值
long mondayMill = dateMill - 86400000 * (weekNumber - 2);
for (int i = 0; i < 7; i++) {
weekMillisList.add(mondayMill + 86400000 * i);
}
return weekMillisList;
}
/**
* 把格式化过的时间转换毫秒值
* @param time 时间
* @param formatSrt 时间格式 如 yyyy-MM-dd
* @return 当前日期的毫秒值
*/
public static long getMillis(String time, String formatSrt) throws ParseException {
@SuppressLint("SimpleDateFormat") SimpleDateFormat format = new SimpleDateFormat(formatSrt);
return format.parse(time).getTime();
}
获取每个自然月的第一天
/**
* get first date of given month and year
* @param year
* @param month
* @return
*/
public static String getFirstDayOfMonth(int year, int month) {
String monthStr = month < 10 ? "0" + month : String.valueOf(month);
return year + "-" + monthStr + "-" + "01";
}
获取每个自然月的最后一天
public static String getLastDayOfMonth(int year, int month) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1);
calendar.set(Calendar.DATE, 1);
calendar.add(Calendar.MONTH, 1);
calendar.add(Calendar.DAY_OF_YEAR, -1);
return calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-" +
calendar.get(Calendar.DAY_OF_MONTH);
}
获取本月所有日期
/**
* 获取本月所有日期
*/
public static List<Date> getAllTheDateOftheMonth(Date date) {
List<Date> list = new ArrayList<Date>();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DATE, 1);
int month = cal.get(Calendar.MONTH);
while (cal.get(Calendar.MONTH) == month) {
list.add(cal.getTime());
cal.add(Calendar.DATE, 1);
}
return list;
}
以下时间工具不太推荐,当做笔记记录
获取每个自然周的第一天
/**
* 输入时间加上1天再格式化
* @param timeString 输入的时间(格式:2017-12-12)
* @return 加过1天的时间
*/
public static String getOneDayIncreaseTime(String timeString) {
String timeStamp = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d;
try {
d = sdf.parse(timeString);
//输入的时间加上1天的时间戳
long l = d.getTime() + 86400000L;
//单位秒
timeStamp = sdf.format(new Date(l));
} catch (ParseException e) {
e.printStackTrace();
}
return timeStamp;
}
输入时间加上90天再格式化
/**
* 输入时间加上90天再格式化
* @param timeString 输入的时间(格式:2017-12-12)
* @return 加过90天的时间
*/
public static String getIncreaseTime(String timeString) {
String timeStamp = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d;
try {
d = sdf.parse(timeString);
//输入的时间加上90天的时间戳
long l = d.getTime() + 7776000000L;
//单位秒
timeStamp = sdf.format(new Date(l));
} catch (ParseException e) {
e.printStackTrace();
}
return timeStamp;
}
加密工具
常用加密方式有:MD5,HMAC,RSA,SHA等
MD5工具类
public class MD5Util {
public final static String MD5(String s) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
try {
byte[] btInput = s.getBytes();
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘要
mdInst.update(btInput);
// 获得密文
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
return null;
}
}
public static void main(String[] args) {
System.out.print(MD5Util.MD5("password"));
}
}
MD5,HMAC,RSA,SHA等相关工具
以下部分,借鉴与此
jdk1.8 - 代码所用jar包maven坐标
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
EncryptionUtil
package org.egg.utils;
import org.apache.commons.codec.binary.Hex;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* @author dataochen
* @Description 各种加密工具类
* @date: 2017/11/7 18:11
*/
public class EncryptionUtil {
private static final String KEY_SHA = "SHA";
private static final String KEY_MD5 = "MD5";
/**
* MAC算法可选以下多种算法
* <p/>
* <pre>
* HmacMD5
* HmacSHA1
* HmacSHA256
* HmacSHA384
* HmacSHA512
* </pre>
*/
public static final String KEY_MAC = "HmacMD5";
/**
* BASE64解密
*
* @param key
* @return
* @throws Exception
*/
public static byte[] decryptBASE64(String key) throws Exception {
return (new BASE64Decoder()).decodeBuffer(key);
}
/**
* BASE64加密
*
* @param key
* @return
* @throws Exception
*/
public static String encryptBASE64(byte[] key) throws Exception {
return (new BASE64Encoder()).encodeBuffer(key);
}
/**
* MD5加密
*
* @param data
* @return
* @throws Exception
*/
public static byte[] encryptMD5(byte[] data) throws Exception {
MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);
md5.update(data);
return md5.digest();
}
/**
* SHA加密
*
* @param data
* @return
* @throws Exception
*/
public static byte[] encryptSHA(byte[] data) throws Exception {
MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
sha.update(data);
return sha.digest();
}
/**
* 初始化HMAC密钥
*
* @return
* @throws Exception
*/
public static String initMacKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);
SecretKey secretKey = keyGenerator.generateKey();
return encryptBASE64(secretKey.getEncoded());
}
/**
* HMAC加密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] encryptHMAC(byte[] data, String key) throws Exception {
SecretKey secretKey = new SecretKeySpec(decryptBASE64(key), KEY_MAC);
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
mac.init(secretKey);
return mac.doFinal(data);
}
/**
* 随机生成密钥对
*/
public static void genKeyPair(String filePath) {
// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
KeyPairGenerator keyPairGen = null;
try {
keyPairGen = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 初始化密钥对生成器,密钥大小为96-1024位
keyPairGen.initialize(1024,new SecureRandom());
// 生成一个密钥对,保存在keyPair中
KeyPair keyPair = keyPairGen.generateKeyPair();
// 得到私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
// 得到公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
try {
// 得到公钥字符串
String publicKeyString = BASE64.encode(publicKey.getEncoded());
// 得到私钥字符串
String privateKeyString = BASE64.encode(privateKey.getEncoded());
// 将密钥对写入到文件
FileWriter pubfw = new FileWriter(filePath + "/publicKey.keystore");
FileWriter prifw = new FileWriter(filePath + "/privateKey.keystore");
BufferedWriter pubbw = new BufferedWriter(pubfw);
BufferedWriter pribw = new BufferedWriter(prifw);
pubbw.write(publicKeyString);
pribw.write(privateKeyString);
pubbw.flush();
pubbw.close();
pubfw.close();
pribw.flush();
pribw.close();
prifw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 从字符串中加载公钥
*
* @param publicKeyStr
* 公钥数据字符串
* @throws Exception
* 加载公钥时产生的异常
*/
public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr)
throws Exception {
try {
byte[] buffer = BASE64.decode(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("公钥非法");
} catch (NullPointerException e) {
throw new Exception("公钥数据为空");
}
}
public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)
throws Exception {
try {
byte[] buffer = BASE64.decode(privateKeyStr);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("私钥非法");
} catch (NullPointerException e) {
throw new Exception("私钥数据为空");
}
}
/**
* RSA 加密返回byte[]
*
* @param content
* @param privateKey
* @return
* @throws Exception
*/
public static byte[] encodeBytePrivate(byte[] content, String privateKey) throws Exception {
PrivateKey key = loadPrivateKeyByStr(privateKey);
return encodeBytePrivate(content, key);
}
/**
* RSA 加密返回byte[]
*
* @param content
* @param privateKey
* @return
* @throws Exception
*/
public static byte[] encodeBytePrivate(byte[] content, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return cipher.doFinal(content);
}
/**
* 解密返回byte[]
*
* @param content
* @param publicKey
* @return
* @throws Exception
*/
public static byte[] decodeBytePublic(byte[] content, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return cipher.doFinal(content);
}
/**
* 解密返回byte[]
*
* @param content
* @param publicKey
* @return
* @throws Exception
*/
public static byte[] decodeBytePublic(byte[] content, String publicKey) throws Exception {
PublicKey key = loadPublicKeyByStr(publicKey);
return decodeBytePublic(content, key);
}
/**
* MD5摘要
*
* @param s
* @return
*/
public final static String md5(String s,String charset) {
try {
byte[] btInput = s.getBytes(charset);
// 获得MD5摘要算法�?MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘�?
mdInst.update(btInput);
// 获得密文
byte[] md = mdInst.digest();
return Hex.encodeHexString(md);
} catch (Exception e) {
return null;
}
}
}
BASE64.java
package org.egg.utils;
import java.io.UnsupportedEncodingException;
/**
* @author dataochen
* @Description
* @date: 2017/11/7 18:12
*/
public class BASE64 {
/**
* Default values for encoder/decoder flags.
*/
public static final int DEFAULT = 0;
/**
* Encoder flag bit to omit the padding '=' characters at the end
* of the output (if any).
*/
public static final int NO_PADDING = 1;
/**
* Encoder flag bit to omit all line terminators (i.e., the output
* will be on one long line).
*/
public static final int NO_WRAP = 2;
/**
* Encoder flag bit to indicate lines should be terminated with a
* CRLF pair instead of just an LF. Has no effect if {@code
* NO_WRAP} is specified as well.
*/
public static final int CRLF = 4;
/**
* Encoder/decoder flag bit to indicate using the "URL and
* filename safe" variant of Base64 (see RFC 3548 section 4) where
* {@code -} and {@code _} are used in place of {@code +} and
* {@code /}.
*/
public static final int URL_SAFE = 8;
/**
* Flag to pass to {@link org.apache.commons.codec.binary.Base64OutputStream} to indicate that it
* should not close the output stream it is wrapping when it
* itself is closed.
*/
public static final int NO_CLOSE = 16;
// --------------------------------------------------------
// shared code
// --------------------------------------------------------
/* package */ static abstract class Coder {
public byte[] output;
public int op;
/**
* Encode/decode another block of input data. this.output is
* provided by the caller, and must be big enough to hold all
* the coded data. On exit, this.opwill be set to the length
* of the coded data.
*
* @param finish true if this is the final call to process for
* this object. Will finalize the coder state and
* include any final bytes in the output.
*
* @return true if the input so far is good; false if some
* error has been detected in the input stream..
*/
public abstract boolean process(byte[] input, int offset, int len, boolean finish);
/**
* @return the maximum number of bytes a call to process()
* could produce for the given number of input bytes. This may
* be an overestimate.
*/
public abstract int maxOutputSize(int len);
}
// --------------------------------------------------------
// decoding
// --------------------------------------------------------
/**
* Decode the Base64-encoded data in input and return the data in
* a new byte array.
*
* <p>The padding '=' characters at the end are considered optional, but
* if any are present, there must be the correct number of them.
*
* @param str the input String to decode, which is converted to
* bytes using the default charset
* @param flags controls certain features of the decoded output.
* Pass {@code DEFAULT} to decode standard Base64.
*
* @throws IllegalArgumentException if the input contains
* incorrect padding
*/
public static byte[] decode(String str, int flags) {
return decode(str.getBytes(), flags);
}
/**
* Decode the Base64-encoded data in input and return the data in
* a new byte array.
*
* <p>The padding '=' characters at the end are considered optional, but
* if any are present, there must be the correct number of them.
*
* @param input the input array to decode
* @param flags controls certain features of the decoded output.
* Pass {@code DEFAULT} to decode standard Base64.
*
* @throws IllegalArgumentException if the input contains
* incorrect padding
*/
public static byte[] decode(byte[] input, int flags) {
return decode(input, 0, input.length, flags);
}
/**
* Decode the Base64-encoded data in input and return the data in
* a new byte array.
*
* <p>The padding '=' characters at the end are considered optional, but
* if any are present, there must be the correct number of them.
*
* @param input the data to decode
* @param offset the position within the input array at which to start
* @param len the number of bytes of input to decode
* @param flags controls certain features of the decoded output.
* Pass {@code DEFAULT} to decode standard Base64.
*
* @throws IllegalArgumentException if the input contains
* incorrect padding
*/
public static byte[] decode(byte[] input, int offset, int len, int flags) {
// Allocate space for the most data the input could represent.
// (It could contain less if it contains whitespace, etc.)
Decoder decoder = new Decoder(flags, new byte[len*3/4]);
if (!decoder.process(input, offset, len, true)) {
throw new IllegalArgumentException("bad base-64");
}
// Maybe we got lucky and allocated exactly enough output space.
if (decoder.op == decoder.output.length) {
return decoder.output;
}
// Need to shorten the array, so allocate a new one of the
// right size and copy.
byte[] temp = new byte[decoder.op];
System.arraycopy(decoder.output, 0, temp, 0, decoder.op);
return temp;
}
/* package */ static class Decoder extends Coder {
/**
* Lookup table for turning bytes into their position in the
* Base64 alphabet.
*/
private static final int DECODE[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
};
/**
* Decode lookup table for the "web safe" variant (RFC 3548
* sec. 4) where - and _ replace + and /.
*/
private static final int DECODE_WEBSAFE[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
};
/** Non-data values in the DECODE arrays. */
private static final int SKIP = -1;
private static final int EQUALS = -2;
/**
* States 0-3 are reading through the next input tuple.
* State 4 is having read one '=' and expecting exactly
* one more.
* State 5 is expecting no more data or padding characters
* in the input.
* State 6 is the error state; an error has been detected
* in the input and no future input can "fix" it.
*/
private int state; // state number (0 to 6)
private int value;
final private int[] alphabet;
public Decoder(int flags, byte[] output) {
this.output = output;
alphabet = ((flags & URL_SAFE) == 0) ? DECODE : DECODE_WEBSAFE;
state = 0;
value = 0;
}
/**
* @return an overestimate for the number of bytes {@code
* len} bytes could decode to.
*/
@Override
public int maxOutputSize(int len) {
return len * 3/4 + 10;
}
/**
* Decode another block of input data.
*
* @return true if the state machine is still healthy. false if
* bad base-64 data has been detected in the input stream.
*/
@Override
public boolean process(byte[] input, int offset, int len, boolean finish) {
if (this.state == 6) {
return false;
}
int p = offset;
len += offset;
// Using local variables makes the decoder about 12%
// faster than if we manipulate the member variables in
// the loop. (Even alphabet makes a measurable
// difference, which is somewhat surprising to me since
// the member variable is final.)
int state = this.state;
int value = this.value;
int op = 0;
final byte[] output = this.output;
final int[] alphabet = this.alphabet;
while (p < len) {
// Try the fast path: we're starting a new tuple and the
// next four bytes of the input stream are all data
// bytes. This corresponds to going through states
// 0-1-2-3-0. We expect to use this method for most of
// the data.
//
// If any of the next four bytes of input are non-data
// (whitespace, etc.), value will end up negative. (All
// the non-data values in decode are small negative
// numbers, so shifting any of them up and or'ing them
// together will result in a value with its top bit set.)
//
// You can remove this whole block and the output should
// be the same, just slower.
if (state == 0) {
while (p+4 <= len &&
(value = ((alphabet[input[p] & 0xff] << 18) |
(alphabet[input[p+1] & 0xff] << 12) |
(alphabet[input[p+2] & 0xff] << 6) |
(alphabet[input[p+3] & 0xff]))) >= 0) {
output[op+2] = (byte) value;
output[op+1] = (byte) (value >> 8);
output[op] = (byte) (value >> 16);
op += 3;
p += 4;
}
if (p >= len) {
break;
}
}
// The fast path isn't available -- either we've read a
// partial tuple, or the next four input bytes aren't all
// data, or whatever. Fall back to the slower state
// machine implementation.
int d = alphabet[input[p++] & 0xff];
switch (state) {
case 0:
if (d >= 0) {
value = d;
++state;
} else if (d != SKIP) {
this.state = 6;
return false;
}
break;
case 1:
if (d >= 0) {
value = (value << 6) | d;
++state;
} else if (d != SKIP) {
this.state = 6;
return false;
}
break;
case 2:
if (d >= 0) {
value = (value << 6) | d;
++state;
} else if (d == EQUALS) {
// Emit the last (partial) output tuple;
// expect exactly one more padding character.
output[op++] = (byte) (value >> 4);
state = 4;
} else if (d != SKIP) {
this.state = 6;
return false;
}
break;
case 3:
if (d >= 0) {
// Emit the output triple and return to state 0.
value = (value << 6) | d;
output[op+2] = (byte) value;
output[op+1] = (byte) (value >> 8);
output[op] = (byte) (value >> 16);
op += 3;
state = 0;
} else if (d == EQUALS) {
// Emit the last (partial) output tuple;
// expect no further data or padding characters.
output[op+1] = (byte) (value >> 2);
output[op] = (byte) (value >> 10);
op += 2;
state = 5;
} else if (d != SKIP) {
this.state = 6;
return false;
}
break;
case 4:
if (d == EQUALS) {
++state;
} else if (d != SKIP) {
this.state = 6;
return false;
}
break;
case 5:
if (d != SKIP) {
this.state = 6;
return false;
}
break;
}
}
if (!finish) {
// We're out of input, but a future call could provide
// more.
this.state = state;
this.value = value;
this.op = op;
return true;
}
// Done reading input. Now figure out where we are left in
// the state machine and finish up.
switch (state) {
case 0:
// Output length is a multiple of three. Fine.
break;
case 1:
// Read one extra input byte, which isn't enough to
// make another output byte. Illegal.
this.state = 6;
return false;
case 2:
// Read two extra input bytes, enough to emit 1 more
// output byte. Fine.
output[op++] = (byte) (value >> 4);
break;
case 3:
// Read three extra input bytes, enough to emit 2 more
// output bytes. Fine.
output[op++] = (byte) (value >> 10);
output[op++] = (byte) (value >> 2);
break;
case 4:
// Read one padding '=' when we expected 2. Illegal.
this.state = 6;
return false;
case 5:
// Read all the padding '='s we expected and no more.
// Fine.
break;
}
this.state = state;
this.op = op;
return true;
}
}
// --------------------------------------------------------
// encoding
// --------------------------------------------------------
/**
* Base64-encode the given data and return a newly allocated
* String with the result.
*
* @param input the data to encode
* @param flags controls certain features of the encoded output.
* Passing {@code DEFAULT} results in output that
* adheres to RFC 2045.
*/
public static String encodeToString(byte[] input, int flags) {
try {
return new String(encode(input, flags), "US-ASCII");
} catch (UnsupportedEncodingException e) {
// US-ASCII is guaranteed to be available.
throw new AssertionError(e);
}
}
/**
* Base64-encode the given data and return a newly allocated
* String with the result.
*
* @param input the data to encode
* @param offset the position within the input array at which to
* start
* @param len the number of bytes of input to encode
* @param flags controls certain features of the encoded output.
* Passing {@code DEFAULT} results in output that
* adheres to RFC 2045.
*/
public static String encodeToString(byte[] input, int offset, int len, int flags) {
try {
return new String(encode(input, offset, len, flags), "US-ASCII");
} catch (UnsupportedEncodingException e) {
// US-ASCII is guaranteed to be available.
throw new AssertionError(e);
}
}
/**
* Base64-encode the given data and return a newly allocated
* byte[] with the result.
*
* @param input the data to encode
* @param flags controls certain features of the encoded output.
* Passing {@code DEFAULT} results in output that
* adheres to RFC 2045.
*/
public static byte[] encode(byte[] input, int flags) {
return encode(input, 0, input.length, flags);
}
/**
* Base64-encode the given data and return a newly allocated
* byte[] with the result.
*
* @param input the data to encode
* @param offset the position within the input array at which to
* start
* @param len the number of bytes of input to encode
* @param flags controls certain features of the encoded output.
* Passing {@code DEFAULT} results in output that
* adheres to RFC 2045.
*/
public static byte[] encode(byte[] input, int offset, int len, int flags) {
Encoder encoder = new Encoder(flags, null);
// Compute the exact length of the array we will produce.
int output_len = len / 3 * 4;
// Account for the tail of the data and the padding bytes, if any.
if (encoder.do_padding) {
if (len % 3 > 0) {
output_len += 4;
}
} else {
switch (len % 3) {
case 0: break;
case 1: output_len += 2; break;
case 2: output_len += 3; break;
}
}
// Account for the newlines, if any.
if (encoder.do_newline && len > 0) {
output_len += (((len-1) / (3 * Encoder.LINE_GROUPS)) + 1) *
(encoder.do_cr ? 2 : 1);
}
encoder.output = new byte[output_len];
encoder.process(input, offset, len, true);
assert encoder.op == output_len;
return encoder.output;
}
/* package */ static class Encoder extends Coder {
/**
* Emit a new line every this many output tuples. Corresponds to
* a 76-character line length (the maximum allowable according to
* <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>).
*/
public static final int LINE_GROUPS = 19;
/**
* Lookup table for turning Base64 alphabet positions (6 bits)
* into output bytes.
*/
private static final byte ENCODE[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/',
};
/**
* Lookup table for turning Base64 alphabet positions (6 bits)
* into output bytes.
*/
private static final byte ENCODE_WEBSAFE[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_',
};
final private byte[] tail;
/* package */ int tailLen;
private int count;
final public boolean do_padding;
final public boolean do_newline;
final public boolean do_cr;
final private byte[] alphabet;
public Encoder(int flags, byte[] output) {
this.output = output;
do_padding = (flags & NO_PADDING) == 0;
do_newline = (flags & NO_WRAP) == 0;
do_cr = (flags & CRLF) != 0;
alphabet = ((flags & URL_SAFE) == 0) ? ENCODE : ENCODE_WEBSAFE;
tail = new byte[2];
tailLen = 0;
count = do_newline ? LINE_GROUPS : -1;
}
/**
* @return an overestimate for the number of bytes {@code
* len} bytes could encode to.
*/
@Override
public int maxOutputSize(int len) {
return len * 8/5 + 10;
}
@Override
public boolean process(byte[] input, int offset, int len, boolean finish) {
// Using local variables makes the encoder about 9% faster.
final byte[] alphabet = this.alphabet;
final byte[] output = this.output;
int op = 0;
int count = this.count;
int p = offset;
len += offset;
int v = -1;
// First we need to concatenate the tail of the previous call
// with any input bytes available now and see if we can empty
// the tail.
switch (tailLen) {
case 0:
// There was no tail.
break;
case 1:
if (p+2 <= len) {
// A 1-byte tail with at least 2 bytes of
// input available now.
v = ((tail[0] & 0xff) << 16) |
((input[p++] & 0xff) << 8) |
(input[p++] & 0xff);
tailLen = 0;
};
break;
case 2:
if (p+1 <= len) {
// A 2-byte tail with at least 1 byte of input.
v = ((tail[0] & 0xff) << 16) |
((tail[1] & 0xff) << 8) |
(input[p++] & 0xff);
tailLen = 0;
}
break;
}
if (v != -1) {
output[op++] = alphabet[(v >> 18) & 0x3f];
output[op++] = alphabet[(v >> 12) & 0x3f];
output[op++] = alphabet[(v >> 6) & 0x3f];
output[op++] = alphabet[v & 0x3f];
if (--count == 0) {
if (do_cr) {
output[op++] = '\r';
}
output[op++] = '\n';
count = LINE_GROUPS;
}
}
// At this point either there is no tail, or there are fewer
// than 3 bytes of input available.
// The main loop, turning 3 input bytes into 4 output bytes on
// each iteration.
while (p+3 <= len) {
v = ((input[p] & 0xff) << 16) |
((input[p+1] & 0xff) << 8) |
(input[p+2] & 0xff);
output[op] = alphabet[(v >> 18) & 0x3f];
output[op+1] = alphabet[(v >> 12) & 0x3f];
output[op+2] = alphabet[(v >> 6) & 0x3f];
output[op+3] = alphabet[v & 0x3f];
p += 3;
op += 4;
if (--count == 0) {
if (do_cr) {
output[op++] = '\r';
}
output[op++] = '\n';
count = LINE_GROUPS;
}
}
if (finish) {
// Finish up the tail of the input. Note that we need to
// consume any bytes in tail before any bytes
// remaining in input; there should be at most two bytes
// total.
if (p-tailLen == len-1) {
int t = 0;
v = ((tailLen > 0 ? tail[t++] : input[p++]) & 0xff) << 4;
tailLen -= t;
output[op++] = alphabet[(v >> 6) & 0x3f];
output[op++] = alphabet[v & 0x3f];
if (do_padding) {
output[op++] = '=';
output[op++] = '=';
}
if (do_newline) {
if (do_cr) {
output[op++] = '\r';
}
output[op++] = '\n';
}
} else if (p-tailLen == len-2) {
int t = 0;
v = (((tailLen > 1 ? tail[t++] : input[p++]) & 0xff) << 10) |
(((tailLen > 0 ? tail[t++] : input[p++]) & 0xff) << 2);
tailLen -= t;
output[op++] = alphabet[(v >> 12) & 0x3f];
output[op++] = alphabet[(v >> 6) & 0x3f];
output[op++] = alphabet[v & 0x3f];
if (do_padding) {
output[op++] = '=';
}
if (do_newline) {
if (do_cr) {
output[op++] = '\r';
}
output[op++] = '\n';
}
} else if (do_newline && op > 0 && count != LINE_GROUPS) {
if (do_cr) {
output[op++] = '\r';
}
output[op++] = '\n';
}
assert tailLen == 0;
assert p == len;
} else {
// Save the leftovers in tail to be consumed on the next
// call to encodeInternal.
if (p == len-1) {
tail[tailLen++] = input[p];
} else if (p == len-2) {
tail[tailLen++] = input[p];
tail[tailLen++] = input[p+1];
}
}
this.op = op;
this.count = count;
return true;
}
}
private BASE64() { } // don't instantiate
/**
* BASE64 解码
*
* @param str
* @return String
*/
public static byte[] decode(String str) {
return decode(str, DEFAULT);
}
/**
* BASE64 编码
*
* @param bytes
* @return String
*/
public static String encode(byte[] bytes) {
return encodeToString(bytes, DEFAULT);
}
}
数据相关工具
数据类型转换
double→格式化的String
public static String formatMoney(double d) {
DecimalFormat myformat = new DecimalFormat();
myformat.applyPattern("0.00");
//myformat.applyPattern("###,###.00");
if (0 == d) {
return "0.00";
}
return myformat.format(d);
}
把String转化为double
public static double convertToDouble(String number, double defaultValue) {
if (TextUtils.isEmpty(number)) {
return defaultValue;
}
try {
return Double.parseDouble(number);
} catch (Exception e) {
return defaultValue;
}
}
把String转化为float
public static float convertToFloat(String number, float defaultValue) {
if (TextUtils.isEmpty(number)) {
return defaultValue;
}
try {
return Float.parseFloat(number);
} catch (Exception e) {
return defaultValue;
}
}
数据格式转换
保留两位小数
/**
* 保留两位小数
* @param s
* @param et
*/
public static void keep2Decimal(TextWatcher textWatcher, CharSequence s, EditText et) {
if (s.toString().contains(".")) {
if (s.length() - 1 - s.toString().indexOf(".") > 2) {
s = s.toString().subSequence(0, s.toString().indexOf(".") + 3);
et.removeTextChangedListener(textWatcher);
et.setText(s);
et.setSelection(s.length());
et.addTextChangedListener(textWatcher);
}
}
if (".".equals(s.toString())) {
s = "0" + s;
et.removeTextChangedListener(textWatcher);
et.setText(s);
et.setSelection(2);
et.addTextChangedListener(textWatcher);
}
if (s.toString().startsWith("0") && s.toString().trim().length() > 1 && !".".equals(s.toString().substring(1, 2))) {
et.removeTextChangedListener(textWatcher);
et.setText(s.toString().substring(1, s.length()));
et.setSelection(s.length() - 1);
et.addTextChangedListener(textWatcher);
}
}
使用方式(动态监听)
//控件的文本监听,动态设置保留俩位小数
mPrice.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
ToolUtil.keep2Decimal(this,charSequence,mPrice);
}
@Override
public void afterTextChanged(Editable editable) {
}
});
数据内容校验
比较两个List是否相等(相同元素)
- 方式一:可正常使用,且获取结果正确
public static boolean equals(int[] a, int[] a2) {
if (a==a2) return true;
if (a==null || a2==null) return false;
int length = a.length;
if (a2.length != length) return false;
for (int i=0; i<length; i++)
if (a[i] != a2[i]) return false;
return true;
}
- 方式二:项目中还未使用,此处用于收集
/**
* 首先进行入参检查防止出现空指针异常
* 如果两个参数都为空,则返回true
* 如果有一项为空,则返回false
* 接着对第一个list进行遍历,如果某一项第二个list里面没有,则返回false
* 还要再将两个list反过来比较,因为可能一个list是两一个list的子集
* 如果成功遍历结束,返回true
* @param l0
* @param l1
* @return
*/
public static boolean isListEqual(List l0, List l1){
if (l0 == l1)
return true;
if (l0 == null && l1 == null)
return true;
if (l0 == null || l1 == null)
return false;
if (l0.size() != l1.size())
return false;
for (Object o : l0) {
if (!l1.contains(o))
return false;
}
for (Object o : l1) {
if (!l0.contains(o))
return false;
}
return true;
}
获取两个List的不同元素
/**
* 获取两个List的不同元素
* @param list1
* @param list2
* @return
*/
private static List<String> getDiffrent(List<String> list1, List<String> list2) {
long st = System.nanoTime();
List<String> diff = new ArrayList<String>();
for(String str:list1)
{
if(!list2.contains(str))
{
diff.add(str);
}
}
System.out.println("total times "+(System.nanoTime()-st));
return diff;
}
}
设备信息工具
设备品牌、型号、版本、API、宽高度、设备唯一标识码
获取手机Android 版本(4.4、5.0、5.1 …)
/**
* 获取手机Android 版本(4.4、5.0、5.1 ...)
* @return String
*/
public static String getBuildVersion() {
return Build.VERSION.RELEASE;
}
获取手机Android API等级(22、23 …)
/**
* 获取手机Android API等级(22、23 ...)
* @return int
*/
public static int getBuildLevel() {
return Build.VERSION.SDK_INT;
}
获取手机型号
/**
* 获取手机型号
* @return String
*/
public static String getPhoneModel() {
return Build.MODEL;
}
获取设备的唯一标识
/**
* 获取设备的唯一标识,deviceId
* @param context context
* @return String
*/
public static String getDeviceId(Context context) {
TelephonyManager tm = (TelephonyManager) context.getSystemService(
Context.TELEPHONY_SERVICE);
String deviceId = tm.getDeviceId();
if (deviceId == null) {
return "-";
} else {
return deviceId;
}
}
获取手机品牌
/**
* 获取手机品牌
* @return String
*/
public static String getPhoneBrand() {
return Build.BRAND;
}
获取设备宽度(px)
/**
* 获取设备宽度(px)
* @param context context
* @return int
*/
public static int deviceWidth(Context context) {
return context.getResources().getDisplayMetrics().widthPixels;
}
获取设备高度(px)
/**
* 获取设备高度(px)
*/
public static int deviceHeight(Context context) {
return context.getResources().getDisplayMetrics().heightPixels;
}
获取状态栏高度
/**
* 获取状态栏高度
* @param context context
* @return 状态栏高度
*/
public static int getStatusBarHeight(Context context) {
// 获得状态栏高度
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
return context.getResources().getDimensionPixelSize(resourceId);
}
APP应用信息工具
获取当前展示 的Activity名称
/**
* 获取当前展示 的Activity名称
* @return
*/
private static String getCurrentActivityName(Context context){
ActivityManager activityManager=(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
String runningActivity=activityManager.getRunningTasks(1).get(0).topActivity.getClassName();
return runningActivity;
}
获取当前App进程的id
/**
* 获取当前App进程的id
* @return int
*/
public static int getAppProcessId() {
return android.os.Process.myPid();
}
获取程序的权限
/*
* 获取程序的权限
*/
public String[] getAllPermissions(Context context,String packname){
try {
//包管理操作管理类
PackageManager pm = context.getPackageManager();
PackageInfo packinfo = pm.getPackageInfo(packname, PackageManager.GET_PERMISSIONS);
//获取到所有的权限
return packinfo.requestedPermissions;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
获取程序的签名
/**
* 获取程序的签名
* @param context
* @param packname
* @return
*/
public static String getAppSignature(Context context,String packname){
try {
//包管理操作管理类
PackageManager pm = context.getPackageManager();
PackageInfo packinfo = pm.getPackageInfo(packname, PackageManager.GET_SIGNATURES);
//获取当前应用签名
return packinfo.signatures[0].toCharsString();
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return packname;
}
获取程序 图标
/**
* 获取程序 图标
* @param context
* @param packname 应用包名
* @return
*/
public Drawable getAppIcon(Context context,String packname){
try {
//包管理操作管理类
PackageManager pm = context.getPackageManager();
//获取到应用信息
ApplicationInfo info = pm.getApplicationInfo(packname, 0);
return info.loadIcon(pm);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
获取当前App进程的Name
/**
* 获取当前App进程的Name
* @param context context
* @param processId processId
* @return String
*/
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(DeviceUtils.class.getName(), e.getMessage(), e);
}
}
return processName;
}
获取包名
方式1
/**
* 获取当前应用程序的包名
* @param context 上下文对象
* @return 返回包名
*/
public static String getAppProcessName(Context context) {
//当前应用pid
int pid = android.os.Process.myPid();
//任务管理类
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//遍历所有应用
List<ActivityManager.RunningAppProcessInfo> infos = manager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo info : infos) {
if (info.pid == pid)//得到当前应用
return info.processName;//返回包名
}
return "";
}
方式2
/**
* 获取包名
*/
public static String getPackageName(Context ctx) {
try {
PackageInfo info = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0);
return info.packageName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return null;
}
}
返回版本号
/**
* 返回版本号
* 对应build.gradle中的versionCode
* @param context context
* @return String
*/
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;
}
返回版本名字
/**
* 返回版本名字
* 对应build.gradle中的versionName
* @param context context
* @return String
*/
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;
}
获取AndroidManifest.xml里 的值
/**
* 获取AndroidManifest.xml里 <meta-data>的值
* @param context context
* @param name name
* @return String
*/
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;
}
网络状态工具
是否有网络连接
/**
* 判断是否有网络连接
*
* @param context
* @return
*/
public static boolean isNetworkConnected(Context context) {
if (context != null) {
// 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context
.CONNECTIVITY_SERVICE);
// 获取NetworkInfo对象
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
//判断NetworkInfo对象是否为空
if (networkInfo != null)
return networkInfo.isAvailable();
}
return false;
}
wifi是否开启
/**
* 判断:wifi是否开启
*/
public static boolean isWifiEnabled(Context context) {
ConnectivityManager mgrConn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
TelephonyManager mgrTel = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
return ((mgrConn.getActiveNetworkInfo() != null && mgrConn.getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED) || mgrTel.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS);
}
移动网络是否开启
/**
* 判断:移动网络是否开启
*/
public static boolean isMobile(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
return true;
}
return false;
}
获取当前的网络状态:WIFI/2G/3G/4G
/**
* 获取当前的网络状态:WIFI/2G/3G/4G
*/
public static String GetNetworkType() {
String strNetworkType = "";
//获取系统的连接服务
ConnectivityManager connectivityManager = (ConnectivityManager) MyApplication.getApp().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
// NetworkInfo networkInfo = (ConnectivityManager)MyApplication.getApp().getSystemService(Context.CONNECTIVITY_SERVICE).getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
strNetworkType = "WIFI";
} else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
String _strSubTypeName = networkInfo.getSubtypeName();
Log.e("cocos2d-x", "Network getSubtypeName : " + _strSubTypeName);
// TD-SCDMA networkType is 17
int networkType = networkInfo.getSubtype();
switch (networkType) {
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN: //api<8 : replace by 11
strNetworkType = "2G";
break;
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B: //api<9 : replace by 14
case TelephonyManager.NETWORK_TYPE_EHRPD: //api<11 : replace by 12
case TelephonyManager.NETWORK_TYPE_HSPAP: //api<13 : replace by 15
strNetworkType = "3G";
break;
case TelephonyManager.NETWORK_TYPE_LTE: //api<11 : replace by 13
strNetworkType = "4G";
break;
default:
// http://baike.baidu.com/item/TD-SCDMA 中国移动 联通 电信 三种3G制式
if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA") || _strSubTypeName.equalsIgnoreCase("WCDMA") || _strSubTypeName.equalsIgnoreCase("CDMA2000")) {
strNetworkType = "3G";
} else {
strNetworkType = _strSubTypeName;
}
break;
}
Log.e("cocos2d-x", "Network getSubtype : " + Integer.valueOf(networkType).toString());
}
}
Log.e("cocos2d-x", "Network Type : " + strNetworkType);
return strNetworkType;
}
判断当前网络是否是2G网络
/**
* 判断当前网络是否是2G网络
*
* @param context
* @return boolean
*/
public static boolean is2G(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetInfo != null
&& (activeNetInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_EDGE
|| activeNetInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_GPRS || activeNetInfo
.getSubtype() == TelephonyManager.NETWORK_TYPE_CDMA)) {
return true;
}
return false;
}
获取当前的网络状态 :没有网络-0:WIFI网络1:4G网络-4:3G网络-3:2G网络-2
/**
* 获取当前的网络状态 :没有网络-0:WIFI网络1:4G网络-4:3G网络-3:2G网络-2
* 自定义
*
* @param context
* @return
*/
public static int getAPNType(Context context) {
//结果返回值
int netType = 0;
//获取手机所有连接管理对象
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context
.CONNECTIVITY_SERVICE);
//获取NetworkInfo对象
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
//NetworkInfo对象为空 则代表没有网络
if (networkInfo == null) {
return netType;
}
//否则 NetworkInfo对象不为空 则获取该networkInfo的类型
int nType = networkInfo.getType();
if (nType == ConnectivityManager.TYPE_WIFI) {
//WIFI
netType = 1;
} else if (nType == ConnectivityManager.TYPE_MOBILE) {
int nSubType = networkInfo.getSubtype();
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService
(Context.TELEPHONY_SERVICE);
//3G 联通的3G为UMTS或HSDPA 电信的3G为EVDO
if (nSubType == TelephonyManager.NETWORK_TYPE_LTE
&& !telephonyManager.isNetworkRoaming()) {
netType = 4;
} else if (nSubType == TelephonyManager.NETWORK_TYPE_UMTS
|| nSubType == TelephonyManager.NETWORK_TYPE_HSDPA
|| nSubType == TelephonyManager.NETWORK_TYPE_EVDO_0
&& !telephonyManager.isNetworkRoaming()) {
netType = 3;
//2G 移动和联通的2G为GPRS或EGDE,电信的2G为CDMA
} else if (nSubType == TelephonyManager.NETWORK_TYPE_GPRS
|| nSubType == TelephonyManager.NETWORK_TYPE_EDGE
|| nSubType == TelephonyManager.NETWORK_TYPE_CDMA
&& !telephonyManager.isNetworkRoaming()) {
netType = 2;
} else {
netType = 2;
}
}
return netType;
}
获得本机ip地址
/**
* 获得本机ip地址
*
* @return
*/
public static String GetHostIp() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> ipAddr = intf.getInetAddresses(); ipAddr
.hasMoreElements(); ) {
InetAddress inetAddress = ipAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
} catch (Exception e) {
}
return null;
}
获取本机串号imei
/**
* 获取本机串号imei
*
* @param context
* @return
*/
public static String getIMEI(Context context) {
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
return telephonyManager.getDeviceId();
}
判断是否有外网连接
/***
* 判断是否有外网连接(普通方法不能判断外网的网络是否连接,比如连接上局域网)
*
* @return
*/
public static final boolean ping() {
String result = null;
try {
String ip = "www.baidu.com";// ping 的地址,可以换成任何一种可靠的外网
Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping网址3次
// 读取ping的内容,可以不加
InputStream input = p.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(input));
StringBuffer stringBuffer = new StringBuffer();
String content = "";
while ((content = in.readLine()) != null) {
stringBuffer.append(content);
}
Log.d("------ping-----", "result content : " + stringBuffer.toString());
// ping的状态
int status = p.waitFor();
if (status == 0) {
result = "success";
return true;
} else {
result = "failed";
}
} catch (IOException e) {
result = "IOException";
} catch (InterruptedException e) {
result = "InterruptedException";
} finally {
Log.d("----result---", "result = " + result);
}
return false;
}
判断GPS是否打开
/**
* 判断GPS是否打开
* ACCESS_FINE_LOCATION权限
*
* @param context
* @return
*/
public static boolean isGPSEnabled(Context context) {
//获取手机所有连接LOCATION_SERVICE对象
LocationManager locationManager = ((LocationManager) context.getSystemService(Context
.LOCATION_SERVICE));
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
获取当前网络连接的类型信息
/**
* 获取当前网络连接的类型信息
* 原生
*
* @param context
* @return
*/
public static int getConnectedType(Context context) {
if (context != null) {
//获取手机所有连接管理对象
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context
.CONNECTIVITY_SERVICE);
//获取NetworkInfo对象
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isAvailable()) {
//返回NetworkInfo的类型
return networkInfo.getType();
}
}
return -1;
}
NetWorkTool工具类
因多方拼凑,部分方法重复,但索性较全 ~
package nk.com.networklinstener;
import android.content.Context;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.util.Log;
import java.util.List;
/**
* @author MrLiu
* @date 2020/5/12
* desc 网络状态相关工具
*/
public class NetWorkTool {
/**
* 判断:移动网络是否开启
*/
public static boolean isMobile(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
return true;
}
return false;
}
/**
* 判断:wifi是否开启
*/
public static boolean isWifiEnabled(Context context) {
ConnectivityManager mgrConn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
TelephonyManager mgrTel = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
return ((mgrConn.getActiveNetworkInfo() != null && mgrConn.getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED) || mgrTel.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS);
}
/**
* 判断:网络是否连接
* 兼容新旧API(旧版API有会存在网络,新版相对准确)
*/
public static boolean isNetworkAvailable(Context context) {
if (context == null) {
return false;
}
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//新版本调用方法获取网络状态
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Network[] networks = connectivity.getAllNetworks();
NetworkInfo networkInfo;
for (Network mNetwork : networks) {
networkInfo = connectivity.getNetworkInfo(mNetwork);
if (networkInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
return true;
}
}
} else {
//否则调用旧版本方法
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (NetworkInfo anInfo : info) {
if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
Log.d("Network", "NETWORKNAME: " + anInfo.getTypeName());
return true;
}
}
}
}
}
return false;
}
/**
* 判断:当前网络状态是否连接
*/
public static boolean isConnected(Context context) {
try {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
if (info.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
} catch (Exception e) {
return false;
}
return false;
}
/**
* 判断当前网络是否是2G网络
*
* @param context
* @return boolean
*/
public static boolean is2G(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetInfo != null
&& (activeNetInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_EDGE
|| activeNetInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_GPRS || activeNetInfo
.getSubtype() == TelephonyManager.NETWORK_TYPE_CDMA)) {
return true;
}
return false;
}
/**
* 获取当前的网络状态:WIFI/2G/3G/4G
*/
public static String GetNetworkType() {
String strNetworkType = "";
//获取系统的连接服务
ConnectivityManager connectivityManager = (ConnectivityManager) MyApplication.getApp().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
// NetworkInfo networkInfo = (ConnectivityManager)MyApplication.getApp().getSystemService(Context.CONNECTIVITY_SERVICE).getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
strNetworkType = "WIFI";
} else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
String _strSubTypeName = networkInfo.getSubtypeName();
Log.e("cocos2d-x", "Network getSubtypeName : " + _strSubTypeName);
// TD-SCDMA networkType is 17
int networkType = networkInfo.getSubtype();
switch (networkType) {
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN: //api<8 : replace by 11
strNetworkType = "2G";
break;
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B: //api<9 : replace by 14
case TelephonyManager.NETWORK_TYPE_EHRPD: //api<11 : replace by 12
case TelephonyManager.NETWORK_TYPE_HSPAP: //api<13 : replace by 15
strNetworkType = "3G";
break;
case TelephonyManager.NETWORK_TYPE_LTE: //api<11 : replace by 13
strNetworkType = "4G";
break;
default:
// http://baike.baidu.com/item/TD-SCDMA 中国移动 联通 电信 三种3G制式
if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA") || _strSubTypeName.equalsIgnoreCase("WCDMA") || _strSubTypeName.equalsIgnoreCase("CDMA2000")) {
strNetworkType = "3G";
} else {
strNetworkType = _strSubTypeName;
}
break;
}
Log.e("cocos2d-x", "Network getSubtype : " + Integer.valueOf(networkType).toString());
}
}
Log.e("cocos2d-x", "Network Type : " + strNetworkType);
return strNetworkType;
}
/**
* 获取当前的网络状态 :没有网络-0:WIFI网络1:4G网络-4:3G网络-3:2G网络-2
* 自定义
*
* @param context
* @return
*/
public static int getAPNType(Context context) {
//结果返回值
int netType = 0;
//获取手机所有连接管理对象
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context
.CONNECTIVITY_SERVICE);
//获取NetworkInfo对象
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
//NetworkInfo对象为空 则代表没有网络
if (networkInfo == null) {
return netType;
}
//否则 NetworkInfo对象不为空 则获取该networkInfo的类型
int nType = networkInfo.getType();
if (nType == ConnectivityManager.TYPE_WIFI) {
//WIFI
netType = 1;
} else if (nType == ConnectivityManager.TYPE_MOBILE) {
int nSubType = networkInfo.getSubtype();
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService
(Context.TELEPHONY_SERVICE);
//3G 联通的3G为UMTS或HSDPA 电信的3G为EVDO
if (nSubType == TelephonyManager.NETWORK_TYPE_LTE
&& !telephonyManager.isNetworkRoaming()) {
netType = 4;
} else if (nSubType == TelephonyManager.NETWORK_TYPE_UMTS
|| nSubType == TelephonyManager.NETWORK_TYPE_HSDPA
|| nSubType == TelephonyManager.NETWORK_TYPE_EVDO_0
&& !telephonyManager.isNetworkRoaming()) {
netType = 3;
//2G 移动和联通的2G为GPRS或EGDE,电信的2G为CDMA
} else if (nSubType == TelephonyManager.NETWORK_TYPE_GPRS
|| nSubType == TelephonyManager.NETWORK_TYPE_EDGE
|| nSubType == TelephonyManager.NETWORK_TYPE_CDMA
&& !telephonyManager.isNetworkRoaming()) {
netType = 2;
} else {
netType = 2;
}
}
return netType;
}
/**
* 判断GPS是否打开
* ACCESS_FINE_LOCATION权限
*
* @param context
* @return
*/
public static boolean isGPSEnabled(Context context) {
//获取手机所有连接LOCATION_SERVICE对象
LocationManager locationManager = ((LocationManager) context.getSystemService(Context
.LOCATION_SERVICE));
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
/**
* 获得本机ip地址
*
* @return
*/
public static String GetHostIp() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> ipAddr = intf.getInetAddresses(); ipAddr
.hasMoreElements(); ) {
InetAddress inetAddress = ipAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
} catch (Exception e) {
}
return null;
}
/**
* 获取本机串号imei
*
* @param context
* @return
*/
public static String getIMEI(Context context) {
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
return telephonyManager.getDeviceId();
}
/***
* 判断是否有外网连接(普通方法不能判断外网的网络是否连接,比如连接上局域网)
*
* @return
*/
public static final boolean ping() {
String result = null;
try {
String ip = "www.baidu.com";// ping 的地址,可以换成任何一种可靠的外网
Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping网址3次
// 读取ping的内容,可以不加
InputStream input = p.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(input));
StringBuffer stringBuffer = new StringBuffer();
String content = "";
while ((content = in.readLine()) != null) {
stringBuffer.append(content);
}
Log.d("------ping-----", "result content : " + stringBuffer.toString());
// ping的状态
int status = p.waitFor();
if (status == 0) {
result = "success";
return true;
} else {
result = "failed";
}
} catch (IOException e) {
result = "IOException";
} catch (InterruptedException e) {
result = "InterruptedException";
} finally {
Log.d("----result---", "result = " + result);
}
return false;
}
/**
* 判断当前网络是否是移动网络
*
* @param context
* @return boolean
*/
public static boolean is3G(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetInfo != null
&& activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
return true;
}
return false;
}
/**
* 判断当前网络是否是wifi网络
*
* @param context
* @return boolean
*/
public static boolean isWifi(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetInfo != null
&& activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
}
return false;
}
/**
* 判断当前网络是否是2G网络
*
* @param context
* @return boolean
*/
public static boolean is2G(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetInfo != null
&& (activeNetInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_EDGE
|| activeNetInfo.getSubtype() == TelephonyManager.NETWORK_TYPE_GPRS || activeNetInfo
.getSubtype() == TelephonyManager.NETWORK_TYPE_CDMA)) {
return true;
}
return false;
}
/**
* wifi是否打开
*/
public static boolean isWifiEnabled(Context context) {
ConnectivityManager mgrConn = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
TelephonyManager mgrTel = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
return ((mgrConn.getActiveNetworkInfo() != null && mgrConn
.getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED) || mgrTel
.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS);
}
/**
* 判断是否有网络连接
*
* @param context
* @return
*/
public static boolean isNetworkConnected(Context context) {
if (context != null) {
// 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context
.CONNECTIVITY_SERVICE);
// 获取NetworkInfo对象
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
//判断NetworkInfo对象是否为空
if (networkInfo != null)
return networkInfo.isAvailable();
}
return false;
}
/**
* 判断MOBILE网络是否可用
*
* @param context
* @param context
* @return
*/
public static boolean isMobileConnected(Context context) {
if (context != null) {
//获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context
.CONNECTIVITY_SERVICE);
//获取NetworkInfo对象
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
//判断NetworkInfo对象是否为空 并且类型是否为MOBILE
if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
return networkInfo.isAvailable();
}
return false;
}
/**
* 获取当前网络连接的类型信息
* 原生
*
* @param context
* @return
*/
public static int getConnectedType(Context context) {
if (context != null) {
//获取手机所有连接管理对象
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context
.CONNECTIVITY_SERVICE);
//获取NetworkInfo对象
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isAvailable()) {
//返回NetworkInfo的类型
return networkInfo.getType();
}
}
return -1;
}
/**
* 获取当前的网络状态 :没有网络-0:WIFI网络1:4G网络-4:3G网络-3:2G网络-2
* 自定义
*
* @param context
* @return
*/
public static int getAPNType(Context context) {
//结果返回值
int netType = 0;
//获取手机所有连接管理对象
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context
.CONNECTIVITY_SERVICE);
//获取NetworkInfo对象
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
//NetworkInfo对象为空 则代表没有网络
if (networkInfo == null) {
return netType;
}
//否则 NetworkInfo对象不为空 则获取该networkInfo的类型
int nType = networkInfo.getType();
if (nType == ConnectivityManager.TYPE_WIFI) {
//WIFI
netType = 1;
} else if (nType == ConnectivityManager.TYPE_MOBILE) {
int nSubType = networkInfo.getSubtype();
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService
(Context.TELEPHONY_SERVICE);
//3G 联通的3G为UMTS或HSDPA 电信的3G为EVDO
if (nSubType == TelephonyManager.NETWORK_TYPE_LTE
&& !telephonyManager.isNetworkRoaming()) {
netType = 4;
} else if (nSubType == TelephonyManager.NETWORK_TYPE_UMTS
|| nSubType == TelephonyManager.NETWORK_TYPE_HSDPA
|| nSubType == TelephonyManager.NETWORK_TYPE_EVDO_0
&& !telephonyManager.isNetworkRoaming()) {
netType = 3;
//2G 移动和联通的2G为GPRS或EGDE,电信的2G为CDMA
} else if (nSubType == TelephonyManager.NETWORK_TYPE_GPRS
|| nSubType == TelephonyManager.NETWORK_TYPE_EDGE
|| nSubType == TelephonyManager.NETWORK_TYPE_CDMA
&& !telephonyManager.isNetworkRoaming()) {
netType = 2;
} else {
netType = 2;
}
}
return netType;
}
/**
* 判断GPS是否打开
* ACCESS_FINE_LOCATION权限
*
* @param context
* @return
*/
public static boolean isGPSEnabled(Context context) {
//获取手机所有连接LOCATION_SERVICE对象
LocationManager locationManager = ((LocationManager) context.getSystemService(Context
.LOCATION_SERVICE));
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
/**
* 获得本机ip地址
*
* @return
*/
public static String GetHostIp() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> ipAddr = intf.getInetAddresses(); ipAddr
.hasMoreElements(); ) {
InetAddress inetAddress = ipAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
} catch (Exception e) {
}
return null;
}
/**
* 获取本机串号imei
*
* @param context
* @return
*/
public static String getIMEI(Context context) {
TelephonyManager telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
return telephonyManager.getDeviceId();
}
/***
* 判断是否有外网连接(普通方法不能判断外网的网络是否连接,比如连接上局域网)
*
* @return
*/
public static final boolean ping() {
String result = null;
try {
String ip = "www.baidu.com";// ping 的地址,可以换成任何一种可靠的外网
Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping网址3次
// 读取ping的内容,可以不加
InputStream input = p.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(input));
StringBuffer stringBuffer = new StringBuffer();
String content = "";
while ((content = in.readLine()) != null) {
stringBuffer.append(content);
}
Log.d("------ping-----", "result content : " + stringBuffer.toString());
// ping的状态
int status = p.waitFor();
if (status == 0) {
result = "success";
return true;
} else {
result = "failed";
}
} catch (IOException e) {
result = "IOException";
} catch (InterruptedException e) {
result = "InterruptedException";
} finally {
Log.d("----result---", "result = " + result);
}
return false;
}
}
文件相关工具
SD卡判断
/**
* SD卡判断
* @return boolean
*/
public static boolean isSDCardAvailable() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
创建App文件夹
方式1
/**
* 创建App文件夹
* @param appName appName
* @param application application
* @return String
*/
public static String createAPPFolder(String appName, Application application) {
return createAPPFolder(appName, application, null);
}
方式2
/**
* 创建App文件夹
* @param appName appName
* @param application application
* @param folderName folderName
* @return String
*/
public static String createAPPFolder(String appName, Application application, String folderName) {
File root = Environment.getExternalStorageDirectory();
File folder;
/**
* 如果存在SD卡
*/
if (DeviceUtils.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
/**
* 通过Uri找到File
* @param context context
* @param uri uri
* @return File
*/
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 actualImageColumnIndex = actualImageCursor.getColumnIndexOrThrow(
MediaStore.Images.Media.DATA);
actualImageCursor.moveToFirst();
String imgPath = actualImageCursor.getString(actualImageColumnIndex);
file = new File(imgPath);
} else {
file = new File(uri.getPath());
}
if (actualImageCursor != null) {
actualImageCursor.close();
}
return file;
}
dp、px 转换工具
dp 转化为 px
/**
* dp 转化为 px
* @param context context
* @param dpValue dpValue
* @return int
*/
public static int dp2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
px 转化为 dp
/**
* px 转化为 dp
* @param context context
* @param pxValue pxValue
*/
public static int px2dp(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
px 转化为 sp
/**
* px 转化为 sp
*/
public static int px2sp(Context context, float pxValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue / fontScale + 0.5f);
}
sp 转化为 px
public static int sp2px(Context context, float spValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
字母大小写转换工具
其实java已经封装了字母大小写的方法,如下:
//转大写
toUpperCase());
//转小写
toLowerCase());
转大写
private static String toUpper(String data){
return data.toUpperCase();
}
转小写
private static String toLower(String data){
return data.toLowerCase();
}
图片圆化、渐变工具
获取一个圆角矩形的图片
/**
* 获取一个圆角矩形的图片
*
* @param rgb 图片颜色rgb格式
* @param radis 圆角的弧度大小
* @return
*/
public static Drawable generateDrawable(int rgb, float radis) {
GradientDrawable drawable = new GradientDrawable();
drawable.setShape(GradientDrawable.RECTANGLE);//设置形状为矩形
drawable.setColor(rgb);//设置图片颜色
drawable.setCornerRadius(radis);//设置圆角
return drawable;
}
获取一个背景可渐变的图片Selector
/**
* 获取一个背景可渐变的图片Selector
*
* @param pressed 按压状态下的bg
* @param normal 默认状态的bg
* @return
*/
public static Drawable generateSelector(Drawable pressed, Drawable normal) {
//多种状态的多种图片集合,对应xml格式的selector
StateListDrawable drawable = new StateListDrawable();
//添加多种状态下的图片
drawable.addState(new int[]{android.R.attr.state_pressed}, pressed);
drawable.addState(new int[]{android.R.attr.state_selected}, pressed);
drawable.addState(new int[]{}, normal);
//设置状态选择器的过度动画
if (Build.VERSION.SDK_INT>10){
drawable.setEnterFadeDuration(300);
drawable.setExitFadeDuration(300);
}
return drawable;
}
颜色相关工具
颜色工具类 包括常用的色值 ( 此工具主要是一些色值调用,方便借鉴一下
)
/**
* 颜色工具类 包括常用的色值
*/
public final class ColorsUtil {
/**
* Don't let anyone instantiate this class.
*/
private ColorsUtil() {
throw new Error("Do not need instantiate!");
}
/**
* 白色
*/
public static final int WHITE = 0xffffffff;
/**
* 白色 - 半透明
*/
public static final int WHITE_TRANSLUCENT = 0x80ffffff;
/**
* 黑色
*/
public static final int BLACK = 0xff000000;
/**
* 黑色 - 半透明
*/
public static final int BLACK_TRANSLUCENT = 0x80000000;
/**
* 透明
*/
public static final int TRANSPARENT = 0x00000000;
/**
* 红色
*/
public static final int RED = 0xffff0000;
/**
* 红色 - 半透明
*/
public static final int RED_TRANSLUCENT = 0x80ff0000;
/**
* 红色 - 深的
*/
public static final int RED_DARK = 0xff8b0000;
/**
* 红色 - 深的 - 半透明
*/
public static final int RED_DARK_TRANSLUCENT = 0x808b0000;
/**
* 绿色
*/
public static final int GREEN = 0xff00ff00;
/**
* 绿色 - 半透明
*/
public static final int GREEN_TRANSLUCENT = 0x8000ff00;
/**
* 绿色 - 深的
*/
public static final int GREEN_DARK = 0xff003300;
/**
* 绿色 - 深的 - 半透明
*/
public static final int GREEN_DARK_TRANSLUCENT = 0x80003300;
/**
* 绿色 - 浅的
*/
public static final int GREEN_LIGHT = 0xffccffcc;
/**
* 绿色 - 浅的 - 半透明
*/
public static final int GREEN_LIGHT_TRANSLUCENT = 0x80ccffcc;
/**
* 蓝色
*/
public static final int BLUE = 0xff0000ff;
/**
* 蓝色 - 半透明
*/
public static final int BLUE_TRANSLUCENT = 0x800000ff;
/**
* 蓝色 - 深的
*/
public static final int BLUE_DARK = 0xff00008b;
/**
* 蓝色 - 深的 - 半透明
*/
public static final int BLUE_DARK_TRANSLUCENT = 0x8000008b;
/**
* 蓝色 - 浅的
*/
public static final int BLUE_LIGHT = 0xff36a5E3;
/**
* 蓝色 - 浅的 - 半透明
*/
public static final int BLUE_LIGHT_TRANSLUCENT = 0x8036a5E3;
/**
* 天蓝
*/
public static final int SKYBLUE = 0xff87ceeb;
/**
* 天蓝 - 半透明
*/
public static final int SKYBLUE_TRANSLUCENT = 0x8087ceeb;
/**
* 天蓝 - 深的
*/
public static final int SKYBLUE_DARK = 0xff00bfff;
/**
* 天蓝 - 深的 - 半透明
*/
public static final int SKYBLUE_DARK_TRANSLUCENT = 0x8000bfff;
/**
* 天蓝 - 浅的
*/
public static final int SKYBLUE_LIGHT = 0xff87cefa;
/**
* 天蓝 - 浅的 - 半透明
*/
public static final int SKYBLUE_LIGHT_TRANSLUCENT = 0x8087cefa;
/**
* 灰色
*/
public static final int GRAY = 0xff969696;
/**
* 灰色 - 半透明
*/
public static final int GRAY_TRANSLUCENT = 0x80969696;
/**
* 灰色 - 深的
*/
public static final int GRAY_DARK = 0xffa9a9a9;
/**
* 灰色 - 深的 - 半透明
*/
public static final int GRAY_DARK_TRANSLUCENT = 0x80a9a9a9;
/**
* 灰色 - 暗的
*/
public static final int GRAY_DIM = 0xff696969;
/**
* 灰色 - 暗的 - 半透明
*/
public static final int GRAY_DIM_TRANSLUCENT = 0x80696969;
/**
* 灰色 - 浅的
*/
public static final int GRAY_LIGHT = 0xffd3d3d3;
/**
* 灰色 - 浅的 - 半透明
*/
public static final int GRAY_LIGHT_TRANSLUCENT = 0x80d3d3d3;
/**
* 橙色
*/
public static final int ORANGE = 0xffffa500;
/**
* 橙色 - 半透明
*/
public static final int ORANGE_TRANSLUCENT = 0x80ffa500;
/**
* 橙色 - 深的
*/
public static final int ORANGE_DARK = 0xffff8800;
/**
* 橙色 - 深的 - 半透明
*/
public static final int ORANGE_DARK_TRANSLUCENT = 0x80ff8800;
/**
* 橙色 - 浅的
*/
public static final int ORANGE_LIGHT = 0xffffbb33;
/**
* 橙色 - 浅的 - 半透明
*/
public static final int ORANGE_LIGHT_TRANSLUCENT = 0x80ffbb33;
/**
* 金色
*/
public static final int GOLD = 0xffffd700;
/**
* 金色 - 半透明
*/
public static final int GOLD_TRANSLUCENT = 0x80ffd700;
/**
* 粉色
*/
public static final int PINK = 0xffffc0cb;
/**
* 粉色 - 半透明
*/
public static final int PINK_TRANSLUCENT = 0x80ffc0cb;
/**
* 紫红色
*/
public static final int FUCHSIA = 0xffff00ff;
/**
* 紫红色 - 半透明
*/
public static final int FUCHSIA_TRANSLUCENT = 0x80ff00ff;
/**
* 灰白色
*/
public static final int GRAYWHITE = 0xfff2f2f2;
/**
* 灰白色 - 半透明
*/
public static final int GRAYWHITE_TRANSLUCENT = 0x80f2f2f2;
/**
* 紫色
*/
public static final int PURPLE = 0xff800080;
/**
* 紫色 - 半透明
*/
public static final int PURPLE_TRANSLUCENT = 0x80800080;
/**
* 青色
*/
public static final int CYAN = 0xff00ffff;
/**
* 青色 - 半透明
*/
public static final int CYAN_TRANSLUCENT = 0x8000ffff;
/**
* 青色 - 深的
*/
public static final int CYAN_DARK = 0xff008b8b;
/**
* 青色 - 深的 - 半透明
*/
public static final int CYAN_DARK_TRANSLUCENT = 0x80008b8b;
/**
* 黄色
*/
public static final int YELLOW = 0xffffff00;
/**
* 黄色 - 半透明
*/
public static final int YELLOW_TRANSLUCENT = 0x80ffff00;
/**
* 黄色 - 浅的
*/
public static final int YELLOW_LIGHT = 0xffffffe0;
/**
* 黄色 - 浅的 - 半透明
*/
public static final int YELLOW_LIGHT_TRANSLUCENT = 0x80ffffe0;
/**
* 巧克力色
*/
public static final int CHOCOLATE = 0xffd2691e;
/**
* 巧克力色 - 半透明
*/
public static final int CHOCOLATE_TRANSLUCENT = 0x80d2691e;
/**
* 番茄色
*/
public static final int TOMATO = 0xffff6347;
/**
* 番茄色 - 半透明
*/
public static final int TOMATO_TRANSLUCENT = 0x80ff6347;
/**
* 橙红色
*/
public static final int ORANGERED = 0xffff4500;
/**
* 橙红色 - 半透明
*/
public static final int ORANGERED_TRANSLUCENT = 0x80ff4500;
/**
* 银白色
*/
public static final int SILVER = 0xffc0c0c0;
/**
* 银白色 - 半透明
*/
public static final int SILVER_TRANSLUCENT = 0x80c0c0c0;
/**
* 高光
*/
public static final int HIGHLIGHT = 0x33ffffff;
/**
* 低光
*/
public static final int LOWLIGHT = 0x33000000;
}
获取资源中的颜色
/**
* 获取资源中的颜色
* @param color
* @return
*/
public static int getResourcesColor(int color) {
int ret = 0x00ffffff;
try {
ret = MApplication.gainContext().getResources().getColor(color);
} catch (Exception e) {
}
return ret;
}
获取一个随机的rgb颜色
/**
* 获取一个随机的rgb颜色
* @return
*/
public static int getRandomColor(){
Random random = new Random();
//0-190
int red = random.nextInt(150)+30;
int green = random.nextInt(150)+30;
int blue = random.nextInt(150)+30;
return Color.rgb(red, green, blue);
}
将十六进制 颜色代码 转换为 int
/**
* 将十六进制 颜色代码 转换为 int
*
* @return
*/
public static int HextoColor(String color) {
// #ff00CCFF
String reg = "#[a-f0-9A-F]{8}";
if (!Pattern.matches(reg, color)) {
color = "#00ffffff";
}
return Color.parseColor(color);
}
修改颜色透明度
/**
* 修改颜色透明度
* @param color
* @param alpha
* @return
*/
public static int changeAlpha(int color, int alpha) {
int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
return Color.argb(alpha, red, green, blue);
}
多类型转Bitmap工具
String类型(图片url)转bitmap
public Bitmap returnBitMap(String url) {
URL myFileUrl = null;
Bitmap bitmap = null;
try {
myFileUrl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
private Drawable loadImageFromNetwork(String urladdr) {
Drawable drawable = null;
try {
//judge if has picture locate or not according to filename
drawable = Drawable.createFromStream(new URL(urladdr).openStream(), "image.jpg");
} catch (IOException e) {
Log.d("test", e.getMessage());
}
if (drawable == null) {
Log.d("test", "null drawable");
} else {
Log.d("test", "not null drawable");
}
return drawable;
}
- 本地图片资源文件转为Bitmap
方法1
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.rest_work_stack, null);
或
Bitmap bitmap = BitmapFactory.decodeResource(this.getContext().getResources(), R.drawable.test);
方法2
Bitmap bitmap = ((BitmapDrawable)getResources().getDrawable(R.mipmap.workstack)).getBitmap();
方法3:以文件流的方式,假设在 sdcard 下有 test.png 图片
FileInputStream fis = new FileInputStream("/sdcard/test.png");
Bitmap bitmap = BitmapFactory.decodeStream(fis);
方法4:ResourceStream 的方式,方便把程序的资源图片插入到本地 sqlite 中
Bitmap.bitmap=BitmapFactory.decodeStream(getClass().getResourceAsStream(“/res/drawable/test.png”));