您的位置:首页 > 其它

常用工具类(8/14)

2017-05-04 11:02 190 查看

UI工具类

1.判断是否是小米UI

private static final String KEY_MIUI_VERSION_CODE = "ro.miui.ui.version.code";
private static final String KEY_MIUI_VERSION_NAME = "ro.miui.ui.version.name";
private static final String KEY_MIUI_INTERNAL_STORAGE = "ro.miui.internal.storage";

public static boolean isMIUI() {
try {
//BuildProperties 是一个工具类,下面会给出代码
final BuildProperties prop = BuildProperties.newInstance();
return prop.getProperty(KEY_MIUI_VERSION_CODE, null) != null
|| prop.getProperty(KEY_MIUI_VERSION_NAME, null) != null
|| prop.getProperty(KEY_MIUI_INTERNAL_STORAGE, null) != null;
} catch (final IOException e) {
return false;
}
}


2.判断是否是华为UI

private static final String KEY_EMUI_VERSION_CODE = "ro.build.hw_emui_api_level";
public static boolean isEMUI() {
try {
final BuildProperties prop = BuildProperties.newInstance();
return prop.getProperty(KEY_EMUI_VERSION_CODE, null) != null;
} catch (final IOException e) {
return false;
}
}


3.判断是否是魅族UI

public static boolean isFlyme() {
try {
// Invoke Build.hasSmartBar()通过反射判断是否含有特殊的方法
final Method method = Build.class.getMethod("hasSmartBar");
return method != null;
} catch (final Exception e) {
return false;
}

}


上面的工具类

public class BuildProperties {
private final Properties properties;

private BuildProperties() throws IOException {
properties = new Properties();
properties.load(new FileInputStream(new File(Environment.getRootDirectory(), "build.prop")));
}

public boolean containsKey(final Object key) {
return properties.containsKey(key);
}

public boolean containsValue(final Object value) {
return properties.containsValue(value);
}

public Set<Entry<Object, Object>> entrySet() {
return properties.entrySet();
}

public String getProperty(final String name) {
return properties.getProperty(name);
}

public String getProperty(final String name, final String defaultValue) {
return properties.getProperty(name, defaultValue);
}

public boolean isEmpty() {
return properties.isEmpty();
}

public Enumeration<Object> keys() {
return properties.keys();
}

public Set<Object> keySet() {
return properties.keySet();
}

public int size() {
return properties.size();
}

public Collection<Object> values() {
return properties.values();
}

public static BuildProperties newInstance() throws IOException {
return new BuildProperties();
}
}


4.获取厂家定义的UI

public static String getProperty(String key, String defaultValue) {
String value = defaultValue;
try {
Class<?> c = Class.forName("android.os.SystemProperties");
Method get = c.getMethod("get", String.class, String.class);
value = (String) (get.invoke(c, key, "unknown"));
} catch (Exception e) {
e.printStackTrace();
} finally {
return value;
}
}


5.获取一些版本参数

(1)获取当前应用的版本名:

public static String getVersionName(Activity activity) {
// 获取packagemanager的实例
try {
if (activity == null) {
return "";
}
PackageManager packageManager = activity.getPackageManager();
// getPackageName()是你当前类的包名,0代表是获取版本信息
PackageInfo packInfo = null;
packInfo = packageManager.getPackageInfo(activity.getPackageName(), 0);
version = packInfo.versionName;
} catch (Exception e) {
e.printStackTrace();
}
return version;
}


(2)获取当前应用的版本号


public static int getVersionCode(Activity activity) {
// 获取packagemanager的实例
PackageManager packageManager = activity.getPackageManager();
// getPackageName()是你当前类的包名,0代表是获取版本信息
PackageInfo packInfo = null;
try {
packInfo = packageManager.getPackageInfo(activity.getPackageName(), PackageManager.GET_CONFIGURATIONS);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
int version = packInfo.versionCode;
return version;
}


(3)其他
//获取手机的sdk版本


String sdk = android.os.Build.VERSION.SDK;


// 手机型号


String model=android.os.Build.MODEL;


// android系统版本号
`String release=android.os.Build.VERSION.RELEASE; `


尺寸工具类

1.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);
}


2.px转dp值

// 根据手机的分辨率将px(像素)的单位转成dp
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}


3.dp转px值

public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}


4.sp转dp值

// 将sp值转换为px值
public static int sp2px(Context context, float spValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}


5.获取屏幕宽度(像素)

// 屏幕宽度(像素)
public static int getScreenHeight(Context context) {
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.heightPixels;
}


获取屏幕高度(像素)

// 屏幕高度(像素)
public static int getWindowHeight(Activity activity) {
DisplayMetrics metric = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
return metric.heightPixels;
}


7.获取状态栏高度的像素值

public static int getStatusBarHeight(Context context) {
int result = 0;
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen",
"android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
return result;
}


8.获取当前截屏,包含状态栏

/**
* 获取当前屏幕截图,包含状态栏
*
* @param activity
* @return
*/
public static Bitmap snapShotWithStatusBar(Activity activity)
{
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
int width = getScreenWidth(activity);
int height = getScreenHeight(activity);
Bitmap bp = null;
bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
view.destroyDrawingCache();
return bp;

}


9.获取当前界面,不包含状态栏

/**
* 获取当前屏幕截图,不包含状态栏
*
* @param activity
* @return
*/
public static Bitmap snapShotWithoutStatusBar(Activity activity)
{
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;

int width = getScreenWidth(activity);
int height = getScreenHeight(activity);
Bitmap bp = null;
bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height
- statusBarHeight);
view.destroyDrawingCache();
return bp;

}


Bitmap的工具类

1.bitmap转drawable

public static Drawable bitmapToDrawable(Bitmap bmp){
return new BitmapDrawable(bmp);
}


2.drawable转bitmap

public static Bitmap drawableToBitmap(Drawable drawable) {
// 取 drawable 的长宽
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();

// 取 drawable 的颜色格式
Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Config.ARGB_8888
: Config.RGB_565;
// 建立对应 bitmap
Bitmap bitmap = Bitmap.createBitmap(w, h, config);
// 建立对应 bitmap 的画布
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
// 把 drawable 内容画到画布中
drawable.draw(canvas);
return bitmap;
}


3.bitmap转字节数字流

public static byte[] Bitmap2Bytes(Bitmap bm){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}


4.字节数组转bitmap

private Bitmap Bytes2Bimap(byte[] b){

if(b.length!=0){
return BitmapFactory.decodeByteArray(b, 0, b.length);
}else {
return null;
}
}


5.缩放图片(bitmap)

//传入新的宽度和新的高度
public static Bitmap setBitmapSize(Bitmap bitmap, int newWidth, int newHeight) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float scaleWidth = (newWidth * 1.0f) / width;
float scaleHeight = (newHeight * 1.0f) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
}


6.缩放图片(路径)

/**
* 缩放图片
* @param bitmapPath  图片路径
* @return bitmap
*/
public static Bitmap setBitmapSize(String bitmapPath, float newWidth, float newHeight) {
Bitmap bitmap = BitmapFactory.decodeFile(bitmapPath);
if (bitmap == null) {
Logger.i("bitmap", "bitmap------------>发生未知异常!");
return null;
}
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float scaleWidth = newWidth / width;
float scaleHeight = newHeight / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
}


7.bitmap保存到本地

//file文件传入时需要设定好路径和名字
//格式可以换
public static boolean saveImg(Bitmap bitmap,File file)
{
try {
FileOutputStream out = new FileOutputStream(file);
if(bitmap.compress(Bitmap.CompressFormat.PNG, 100, out))
{
out.flush();
out.close();
}
out.flush();
out.close();
return true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}


8.file取出为bitmap

public static Bitmap getBmp(File file) throws FileNotFoundException {

if (file == null)
return null;
Options o = new Options();
o.inJustDecodeBounds = true;
Bitmap tmp ;
o.inJustDecodeBounds = false;

int rate = (int)(o.outHeight / (float)o.outWidth);
if (rate <= 0)
{
rate = 1;
}
o.inSampleSize = rate;
o.inPurgeable = true;
o.inInputShareable = true;

tmp = BitmapFactory.decodeFile(file.getAbsolutePath(), o);

return tmp;
}


9.bitmap转成圆形

/**
* 把bitmap转成圆形
* */
public static Bitmap toRoundBitmap(Bitmap bitmap){
int width=bitmap.getWidth();
int height=bitmap.getHeight();
int r=0;
//取最短边做边长
if(width<height){
r=width;
}else{
r=height;
}
//构建一个bitmap
Bitmap backgroundBm=Bitmap.createBitmap(width,height,Config.ARGB_8888);
//new一个Canvas,在backgroundBmp上画图
Canvas canvas=new Canvas(backgroundBm);
Paint p=new Paint();
//设置边缘光滑,去掉锯齿
p.setAntiAlias(true);
RectF rect=new RectF(0, 0, r, r);
//通过制定的rect画一个圆角矩形,当圆角X轴方向的半径等于Y轴方向的半径时,
//且都等于r/2时,画出来的圆角矩形就是圆形
canvas.drawRoundRect(rect, r/2, r/2, p);
//设置当两个图形相交时的模式,SRC_IN为取SRC图形相交的部分,多余的将被去掉
p.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
//canvas将bitmap画在backgroundBmp上
canvas.drawBitmap(bitmap, null, rect, p);
return backgroundBm;
}


10.bitmap转成指定半径的圆

public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
if (bitmap == null) {
return bitmap;
}

Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);

final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;

paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);

return output;
}


11.模糊效果

public static Bitmap blurImage(Bitmap bmp)
{
int width = bmp.getWidth();
int height = bmp.getHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, Config.RGB_565);

int pixColor = 0;

int newR = 0;
int newG = 0;
int newB = 0;

int newColor = 0;

int[][] colors = new int[9][3];
for (int i = 1, length = width - 1; i < length; i++)
{
for (int k = 1, len = height - 1; k < len; k++)
{
for (int m = 0; m < 9; m++)
{
int s = 0;
int p = 0;
switch(m)
{
case 0:
s = i - 1;
p = k - 1;
break;
case 1:
s = i;
p = k - 1;
break;
case 2:
s = i + 1;
p = k - 1;
break;
case 3:
s = i + 1;
p = k;
break;
case 4:
s = i + 1;
p = k + 1;
break;
case 5:
s = i;
p = k + 1;
break;
case 6:
s = i - 1;
p = k + 1;
break;
case 7:
s = i - 1;
p = k;
break;
case 8:
s = i;
p = k;
}
pixColor = bmp.getPixel(s, p);
colors[m][0] = Color.red(pixColor);
colors[m][1] = Color.green(pixColor);
colors[m][2] = Color.blue(pixColor);
}

for (int m = 0; m < 9; m++)
{
newR += colors[m][0];
newG += colors[m][1];
newB += colors[m][2];
}

newR = (int) (newR / 9F);
newG = (int) (newG / 9F);
newB = (int) (newB / 9F);

newR = Math.min(255, Math.max(0, newR));
newG = Math.min(255, Math.max(0, newG));
newB = Math.min(255, Math.max(0, newB));

newColor = Color.argb(255, newR, newG, newB);
bitmap.setPixel(i, k, newColor);

newR = 0;
newG = 0;
newB = 0;
}
}

return bitmap;
}


12.高斯模糊

public static Bitmap blurImageAmeliorate(Bitmap bmp)
{
long start = System.currentTimeMillis();
// 高斯矩阵
int[] gauss = new int[] { 1, 2, 1, 2, 4, 2, 1, 2, 1 };

int width = bmp.getWidth();
int height = bmp.getHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, Config.RGB_565);

int pixR = 0;
int pixG = 0;
int pixB = 0;

int pixColor = 0;

int newR = 0;
int newG = 0;
int newB = 0;

int delta = 16; // 值越小图片会越亮,越大则越暗

int idx = 0;
int[] pixels = new int[width * height];
bmp.getPixels(pixels, 0, width, 0, 0, width, height);
for (int i = 1, length = height - 1; i < length; i++)
{
for (int k = 1, len = width - 1; k < len; k++)
{
idx = 0;
for (int m = -1; m <= 1; m++)
{
for (int n = -1; n <= 1; n++)
{
pixColor = pixels[(i + m) * width + k + n];
pixR = Color.red(pixColor);
pixG = Color.green(pixColor);
pixB = Color.blue(pixColor);

newR = newR + (int) (pixR * gauss[idx]);
newG = newG + (int) (pixG * gauss[idx]);
newB = newB + (int) (pixB * gauss[idx]);
idx++;
}
}

newR /= delta;
newG /= delta;
newB /= delta;

newR = Math.min(255, Math.max(0, newR));
newG = Math.min(255, Math.max(0, newG));
newB = Math.min(255, Math.max(0, newB));

pixels[i * width + k] = Color.argb(255, newR, newG, newB);

newR = 0;
newG = 0;
newB = 0;
}
}

bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
long end = System.currentTimeMillis();
Log.d("may", "used time="+(end - start));
return bitmap;
}


13.旋转bitmap

public static Bitmap rotate(Bitmap bitmap,int degree)
{
Matrix matrix = new Matrix();
matrix.postRotate(degree); /*翻转90度*/
int width = bitmap.getWidth();
int height = bitmap.getHeight();
return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
}


14.按照一定比例裁剪

/**
* 按照一定的宽高比例裁剪图片
* @param bitmap
* @param num1 长边的比例
* @param num2 短边的比例
* @return
*/
public static Bitmap ImageCrop(Bitmap bitmap, int num1, int num2,
boolean isRecycled)
{
if (bitmap == null)
{
return null;
}
int w = bitmap.getWidth(); // 得到图片的宽,高
int h = bitmap.getHeight();
int retX, retY;
int nw, nh;
if (w > h)
{
if (h > w * num2 / num1)
{
nw = w;
nh = w * num2 / num1;
retX = 0;
retY = (h - nh) / 2;
} else
{
nw = h * num1 / num2;
nh = h;
retX = (w - nw) / 2;
retY = 0;
}
} else
{
if (w > h * num2 / num1)
{
nh = h;
nw = h * num2 / num1;
retY = 0;
retX = (w - nw) / 2;
} else
{
nh = w * num1 / num2;
nw = w;
retY = (h - nh) / 2;
retX = 0;
}
}
Bitmap bmp = Bitmap.createBitmap(bitmap, retX, retY, nw, nh, null,
false);
if (isRecycled && bitmap != null && !bitmap.equals(bmp)
&& !bitmap.isRecycled())
{
bitmap.recycle();
bitmap = null;
}
return bmp;// Bitmap.createBitmap(bitmap, retX, retY, nw, nh, null,
// false);
}


15.裁剪中间正方形

/**

* @param bitmap      原图
* @param edgeLength  希望得到的正方形部分的边长
* @return  缩放截取正中部分后的位图。
*/
public static Bitmap centerSquareScaleBitmap(Bitmap bitmap, int edgeLength)
{
if(null == bitmap || edgeLength <= 0)
{
return  null;
}

Bitmap result = bitmap;
int widthOrg = bitmap.getWidth();
int heightOrg = bitmap.getHeight();

if(widthOrg > edgeLength && heightOrg > edgeLength)
{
//压缩到一个最小长度是edgeLength的bitmap
int longerEdge = (int)(edgeLength * Math.max(widthOrg, heightOrg) / Math.min(widthOrg, heightOrg));
int scaledWidth = widthOrg > heightOrg ? longerEdge : edgeLength;
int scaledHeight = widthOrg > heightOrg ? edgeLength : longerEdge;
Bitmap scaledBitmap;

try{
scaledBitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true);
}
catch(Exception e){
return null;
}

//从图中截取正中间的正方形部分。
int xTopLeft = (scaledWidth - edgeLength) / 2;
int yTopLeft = (scaledHeight - edgeLength) / 2;

try{
result = Bitmap.createBitmap(scaledBitmap, xTopLeft, yTopLeft, edgeLength, edgeLength);
scaledBitmap.recycle();
}
catch(Exception e){
return null;
}
}

return result;
}


软键盘处理

1.打开软键盘

/**
* 打开软键盘
* @param mEditText
* @param mContext
*/
public static void openKeybord(EditText mEditText, Context mContext) {
InputMethodManager imm = (InputMethodManager) mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
InputMethodManager.HIDE_IMPLICIT_ONLY);
}


2.关闭软键盘

/**
* 关闭软键盘
*
* @param mEditText
* @param mContext
*/
public static void closeKeybord(EditText mEditText, Context mContext) {
InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);

imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
}


3.查询输入法和键盘(代码片)

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
List<InputMethodInfo> methodList = imm.getInputMethodList();
for(InputMethodInfo mi : methodList ) {
CharSequence name = mi.loadLabel(getPackageManager());
Log.e("TAG",name.toString());
}


正则工具类

1.判断邮箱

/**
* @param email
* @return tab 判断邮箱的正则表达式
*/
public static boolean isEmail(String email) {
String str = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
Pattern p = Pattern.compile(str);
Matcher m = p.matcher(email);
return m.matches();
}


2.判断手机号

/**
* 判别手机是否为正确手机号码; 号码段分配如下:
* 移动:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
* 联通:130、131、132、152、155、156、185、186 电信:133、153、180、189、(1349卫通)
*/
public static boolean isMobileNum(String mobiles) {
//      Pattern p = Pattern.compile("^0{0,1}(13[0-9]|15[5-9]|15[0-3]|17[6-8]|18[0-9])[0-9]{8}$");
Pattern p = Pattern.compile("^13[0-9]{9}$|14[0-9]{9}$|15[0-9]{9}$|17[0-9]{9}$|18[0-9]{9}$");

Matcher m = p.matcher(mobiles);
return m.matches();
}


3.判断字符包含字母和数字

/**
* 判断字符串是包含数字并且包含字母
*
* @param str 需要判断的字符串
* @return boolean 都包含数字和字母 为 true  否则为 false
*/
public static boolean getIsNumAndLetter(String str) {
boolean isDigit = false;//定义一个boolean值,用来表示是否包含数字
boolean isLetter = false;//定义一个boolean值,用来表示是否包含字母
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {   //用char包装类中的判断数字的方法判断每一个字符
isDigit = true;
} else if (Character.isLetter(str.charAt(i))) {  //用char包装类中的判断字母的方法判断每一个字符
isLetter = true;
}
}
String regex = "^[a-zA-Z0-9]+$";
boolean isRight = isDigit && isLetter && str.matches(regex);
return isRight;
}


4.判断出身日期(1994-12-07)

public boolean checkBirthday(String strBirthday){
String strPattern = "^\\d{4}\\-\\d{1,2}-\\d{1,2}$";
Pattern p = Pattern.compile(strPattern);
Matcher m = p.matcher(strBirthday);
return m.matches();
}


5.判断身份证号码18位

public boolean checkBirthday(String strBirthday){
String strPattern = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9Xx])$";
Pattern p = Pattern.compile(strPattern);
Matcher m = p.matcher(strBirthday);
return m.matches();
}


6.判断汉字

public boolean checkBirthday(String strBirthday){
String strPattern = "^[\\u4e00-\\u9fa5]+$";
Pattern p = Pattern.compile(strPattern);
Matcher m = p.matcher(strBirthday);
return m.matches();
}


7.判断url

public boolean checkBirthday(String strBirthday){
String strPattern = "[a-zA-z]+://[^\\s]*";
Pattern p = Pattern.compile(strPattern);
Matcher m = p.matcher(strBirthday);
return m.matches();
}


8.判断IP

public boolean checkBirthday(String strBirthday){
String strPattern = "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)";
Pattern p = Pattern.compile(strPattern);
Matcher m = p.matcher(strBirthday);
return m.matches();
}


9.判断正整数

public boolean checkBirthday(String strBirthday){
String strPattern = "^[1-9]\\d*$";
Pattern p = Pattern.compile(strPattern);
Matcher m = p.matcher(strBirthday);
return m.matches();
}


10.判断负整数

public boolean checkBirthday(String strBirthday){
String strPattern = "^-[1-9]\\d*$";
Pattern p = Pattern.compile(strPattern);
Matcher m = p.matcher(strBirthday);
return m.matches();
}


11.判断整数

public boolean checkBirthday(String strBirthday){
String strPattern = "^-?[1-9]\\d*$";
Pattern p = Pattern.compile(strPattern);
Matcher m = p.matcher(strBirthday);
return m.matches();
}


12.判断正浮点数

public boolean checkBirthday(String strBirthday){
String strPattern = "^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*$";
Pattern p = Pattern.compile(strPattern);
Matcher m = p.matcher(strBirthday);
return m.matches();
}


13.判断负浮点数

public boolean checkBirthday(String strBirthday){
String strPattern = "^-[1-9]\\d*\\.\\d*|-0\\.\\d*[1-9]\\d*$";
Pattern p = Pattern.compile(strPattern);
Matcher m = p.matcher(strBirthday);
return m.matches();
}


14.判断车牌号是否正确(包括新能源汽车)

public static boolean isCarnumberNO(String carnumber) {

String carnumRegex = “([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF])|(DF[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1})”;

if (TextUtils.isEmpty(carnumber)) return false;
else return carnumber.matches(carnumRegex);
}


新能源车规则:”[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF])|([DF][A-HJ-NP-Z0-9][0-9]{4}))”

普通汽车规则:”[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}”

时间工具类

1.获取当前系统时间 yy-MM-dd HH:mm:ss

/**
* 获取系统当前时间 "yyyy年MM月dd日   HH:mm:ss"
* <p/>
* return
*/
public static String getCurrentTimes() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
String str = formatter.format(curDate);
return str;

}


2.获取当前系统时间时间戳

long timeMillis = System.currentTimeMillis()/1000;
String sTimeMillis =String.valueOf(timeMillis);


3.比较日期大小

public static int compare_date(String DATE1, String DATE2) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
Date dt1 = df.parse(DATE1);
Date dt2 = df.parse(DATE2);
if (dt1.getTime() > dt2.getTime()) {
System.out.println("dt1 在dt2前");
Loger.e("=============");
return 1;
} else if (dt1.getTime() < dt2.getTime()) {
System.out.println("dt1在dt2后");
Loger.e("++++++++");
return -1;
} else {
Loger.e("------");
return 0;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return 0;
}


常用颜色类

<color name="white">#FFFFFF</color><!--白色 -->
<color name="ivory">#FFFFF0</color><!--象牙色 -->
<color name="lightyellow">#FFFFE0</color><!--亮黄色-->
<color name="yellow">#FFFF00</color><!--黄色 -->
<color name="snow">#FFFAFA</color><!--雪白色 -->
<color name="floralwhite">#FFFAF0</color><!--花白色 -->
<color name="lemonchiffon">#FFFACD</color><!--柠檬绸色 -->
<color name="cornsilk">#FFF8DC</color><!--米绸色 -->
<color name="seashell">#FFF5EE</color><!--海贝色 -->
<color name="lavenderblush">#FFF0F5</color><!--淡紫红 -->
<color name="papayawhip">#FFEFD5</color><!--番木色 -->
<color name="blanchedalmond">#FFEBCD</color><!--白杏色 -->
<color name="mistyrose">#FFE4E1</color><!--浅玫瑰色 -->
<color name="bisque">#FFE4C4</color><!--桔黄色 -->
<color name="moccasin">#FFE4B5</color><!--鹿皮色 -->
<color name="navajowhite">#FFDEAD</color><!--纳瓦白 -->
<color name="peachpuff">#FFDAB9</color><!--桃色 -->
<color name="gold">#FFD700</color><!--金色 -->
<color name="pink">#FFC0CB</color><!--粉红色 -->
<color name="lightpink">#FFB6C1</color><!--亮粉红色-->
<color name="orange">#FFA500</color><!--橙色 -->
<color name="lightsalmon">#FFA07A</color><!--亮肉色 -->
<color name="darkorange">#FF8C00</color><!--暗桔黄色 -->
<color name="coral">#FF7F50</color><!--珊瑚色 -->
<color name="hotpink">#FF69B4</color><!--热粉红色 -->
<color name="tomato">#FF6347</color><!--西红柿色 -->
<color name="orangered">#FF4500</color><!--红橙色 -->
<color name="deeppink">#FF1493</color><!--深粉红色 -->
<color name="fuchsia">#FF00FF</color><!--紫红色 -->
<color name="magenta">#FF00FF</color><!--红紫色 -->
<color name="red">#FF0000</color><!--红色 -->
<color name="oldlace">#FDF5E6</color><!--老花色 -->
<color name="lightgoldenrodyellow">#FAFAD2</color><!--亮金黄色 -->
<color name="linen">#FAF0E6</color><!--亚麻色 -->
<color name="antiquewhite">#FAEBD7</color><!--古董白 -->
<color name="salmon">#FA8072</color><!--鲜肉色 -->
<color name="ghostwhite">#F8F8FF</color><!--幽灵白 -->
<color name="mintcream">#F5FFFA</color><!--薄荷色 -->
<color name="whitesmoke">#F5F5F5</color><!--烟白色 -->
<color name="beige">#F5F5DC</color><!--米色 -->
<color name="wheat">#F5DEB3</color><!--浅黄色 -->
<color name="sandybrown">#F4A460</color><!--沙褐色-->
<color name="azure">#F0FFFF</color><!--天蓝色 -->
<color name="honeydew">#F0FFF0</color><!--蜜色 -->
<color name="aliceblue">#F0F8FF</color><!--艾利斯兰 -->
<color name="khaki">#F0E68C</color><!--黄褐色 -->
<color name="lightcoral">#F08080</color><!--亮珊瑚色 -->
<color name="palegoldenrod">#EEE8AA</color><!--苍麒麟色 -->
<color name="violet">#EE82EE</color><!--紫罗兰色 -->
<color name="darksalmon">#E9967A</color><!--暗肉色 -->
<color name="lavender">#E6E6FA</color><!--淡紫色 -->
<color name="lightcyan">#E0FFFF</color><!--亮青色 -->
<color name="burlywood">#DEB887</color><!--实木色 -->
<color name="plum">#DDA0DD</color><!--洋李色 -->
<color name="gainsboro">#DCDCDC</color><!--淡灰色 -->
<color name="crimson">#DC143C</color><!--暗深红色 -->
<color name="palevioletred">#DB7093</color><!--苍紫罗兰色 -->
<color name="goldenrod">#DAA520</color><!--金麒麟色 -->
<color name="orchid">#DA70D6</color><!--淡紫色 -->
<color name="thistle">#D8BFD8</color><!--蓟色 -->
<color name="lightgray">#D3D3D3</color><!--亮灰色 -->
<color name="lightgrey">#D3D3D3</color><!--亮灰色 -->
<color name="tan">#D2B48C</color><!--茶色 -->
<color name="chocolate">#D2691E</color><!--巧可力色 -->
<color name="peru">#CD853F</color><!--秘鲁色 -->
<color name="indianred">#CD5C5C</color><!--印第安红 -->
<color name="mediumvioletred">#C71585</color><!--中紫罗兰色 -->
<color name="silver">#C0C0C0</color><!--银色 -->
<color name="darkkhaki">#BDB76B</color><!--暗黄褐色 -->
<color name="rosybrown">#BC8F8F</color> <!--褐玫瑰红 -->
<color name="mediumorchid">#BA55D3</color><!--中粉紫色 -->
<color name="darkgoldenrod">#B8860B</color><!--暗金黄色 -->
<color name="firebrick">#B22222</color><!--火砖色 -->
<color name="powderblue">#B0E0E6</color><!--粉蓝色 -->
<color name="lightsteelblue">#B0C4DE</color><!--亮钢兰色 -->
<color name="paleturquoise">#AFEEEE</color><!--苍宝石绿 -->
<color name="greenyellow">#ADFF2F</color><!--黄绿色 -->
<color name="lightblue">#ADD8E6</color><!--亮蓝色 -->
<color name="darkgray">#A9A9A9</color><!--暗灰色 -->
<color name="darkgrey">#A9A9A9</color><!--暗灰色 -->
<color name="brown">#A52A2A</color><!--褐色 -->
<color name="sienna">#A0522D</color><!--赭色 -->
<color name="darkorchid">#9932CC</color><!--暗紫色-->
<color name="palegreen">#98FB98</color><!--苍绿色 -->
<color name="darkviolet">#9400D3</color><!--暗紫罗兰色 -->
<color name="mediumpurple">#9370DB</color><!--中紫色 -->
<color name="lightgreen">#90EE90</color><!--亮绿色 -->
<color name="darkseagreen">#8FBC8F</color><!--暗海兰色 -->
<color name="saddlebrown">#8B4513</color><!--重褐色 -->
<color name="darkmagenta">#8B008B</color><!--暗洋红 -->
<color name="darkred">#8B0000</color><!--暗红色 -->
<color name="blueviolet">#8A2BE2</color><!--紫罗兰蓝色 -->
<color name="lightskyblue">#87CEFA</color><!--亮天蓝色 -->
<color name="skyblue">#87CEEB</color><!--天蓝色 -->
<color name="gray">#808080</color><!--灰色 -->
<color name="grey">#808080</color><!--灰色 -->
<color name="olive">#808000</color><!--橄榄色 -->
<color name="purple">#800080</color><!--紫色 -->
<color name="maroon">#800000</color><!--粟色 -->
<color name="aquamarine">#7FFFD4</color><!--碧绿色-->
<color name="chartreuse">#7FFF00</color><!--黄绿色 -->
<color name="lawngreen">#7CFC00</color><!--草绿色 -->
<color name="mediumslateblue">#7B68EE</color><!--中暗蓝色 -->
<color name="lightslategray">#778899</color><!--亮蓝灰 -->
<color name="lightslategrey">#778899</color><!--亮蓝灰 -->
<color name="slategray">#708090</color><!--灰石色 -->
<color name="slategrey">#708090</color><!--灰石色 -->
<color name="olivedrab">#6B8E23</color><!--深绿褐色 -->
<color name="slateblue">#6A5ACD</color><!--石蓝色 -->
<color name="dimgray">#696969</color><!--暗灰色 -->
<color name="dimgrey">#696969</color><!--暗灰色 -->
<color name="mediumaquamarine">#66CDAA</color><!--中绿色 -->
<color name="cornflowerblue">#6495ED</color><!--菊兰色 -->
<color name="cadetblue">#5F9EA0</color><!--军兰色 -->
<color name="darkolivegreen">#556B2F</color><!--暗橄榄绿  -->
<color name="indigo">#4B0082</color><!--靛青色 -->
<color name="mediumturquoise">#48D1CC</color><!--中绿宝石 -->
<color name="darkslateblue">#483D8B</color><!--暗灰蓝色 -->
<color name="steelblue">#4682B4</color><!--钢兰色 -->
<color name="royalblue">#4169E1</color><!--皇家蓝 -->
<color name="turquoise">#40E0D0</color><!--青绿色 -->
<color name="mediumseagreen">#3CB371</color><!--中海蓝 -->
<color name="limegreen">#32CD32</color><!--橙绿色 -->
<color name="darkslategray">#2F4F4F</color><!--暗瓦灰色 -->
<color name="darkslategrey">#2F4F4F</color><!--暗瓦灰色 -->
<color name="seagreen">#2E8B57</color><!--海绿色 -->
<color name="forestgreen">#228B22</color><!--森林绿 -->
<color name="lightseagreen">#20B2AA</color><!--亮海蓝色 -->
<color name="dodgerblue">#1E90FF</color><!--闪兰色 -->
<color name="midnightblue">#191970</color><!--中灰兰色 -->
<color name="aqua">#00FFFF</color><!--浅绿色 -->
<color name="cyan">#00FFFF</color><!--青色 -->
<color name="springgreen">#00FF7F</color><!--春绿色-->
<color name="lime">#00FF00</color><!--酸橙色 -->
<color name="mediumspringgreen">#00FA9A</color><!--中春绿色 -->
<color name="darkturquoise">#00CED1</color><!--暗宝石绿 -->
<color name="deepskyblue">#00BFFF</color><!--深天蓝色 -->
<color name="darkcyan">#008B8B</color><!--暗青色 -->
<color name="teal">#008080</color><!--水鸭色 -->
<color name="green">#008000</color><!--绿色 -->
<color name="darkgreen">#006400</color><!--暗绿色 -->
<color name="blue">#0000FF</color><!--蓝色 -->
<color name="mediumblue">#0000CD</color><!--中兰色 -->
<color name="darkblue">#00008B</color><!--暗蓝色 -->
<color name="navy">#000080</color><!--海军色 -->
<color name="black">#000000</color><!--黑色 -->


权限申请工具类

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;

/**
* Android 6.0 上权限分为<b>正常</b>和<b>危险</b>级别
* <ul>
* <li>正常级别权限:开发者仅仅需要在AndroidManifext.xml上声明,那么应用就会被允许拥有该权限,如:android.permission.INTERNET</li>
* <li>危险级别权限:开发者需要在AndroidManifext.xml上声明,并且在运行时进行申请,而且用户允许了,应用才会被允许拥有该权限,如:android.permission.WRITE_EXTERNAL_STORAGE</li>
* </ul>
* 有米的以下权限需要在Android6.0上被允许,有米广告sdk才能正常工作,开发者需要在调用有米的任何代码之前,提前让用户允许权限
* <ul>
* <li>必须申请的权限
* <ul>
* <li>android.permission.READ_PHONE_STATE</li>
* <li>android.permission.WRITE_EXTERNAL_STORAGE</li>
* </ul>
* </li>
* <li>可选申请的权限
* <ul>
* <li>android.permission.ACCESS_FINE_LOCATION</li>
* </ul>
* </li>
* </ul>
* <p>Android 6.0 权限申请助手</p>
* Created by Alian on 16-1-12.
*/
public class PermissionHelper {

private static final String TAG = "PermissionHelper";

/**
* 小tips:这里的int数值不能太大,否则不会弹出请求权限提示,测试的时候,改到1000就不会弹出请求了
*/
private final static int READ_PHONE_STATE_CODE = 101;

private final static int WRITE_EXTERNAL_STORAGE_CODE = 102;

private final static int REQUEST_OPEN_APPLICATION_SETTINGS_CODE = 12345;

/**
* 有米 Android SDK 所需要向用户申请的权限列表
*/
private PermissionModel[] mPermissionModels = new PermissionModel[] {
new PermissionModel("电话", Manifest.permission.READ_PHONE_STATE, "我们需要读取手机信息的权限来标识您的身份", READ_PHONE_STATE_CODE),
new PermissionModel("存储空间", Manifest.permission.WRITE_EXTERNAL_STORAGE, "我们需要您允许我们读写你的存储卡,以方便我们临时保存一些数据",
WRITE_EXTERNAL_STORAGE_CODE)
};

private Activity mActivity;

private OnApplyPermissionListener mOnApplyPermissionListener;

public PermissionHelper(Activity activity) {
mActivity = activity;
}

public void setOnApplyPermissionListener(OnApplyPermissionListener onApplyPermissionListener) {
mOnApplyPermissionListener = onApplyPermissionListener;
}

/**
* 这里我们演示如何在Android 6.0+上运行时申请权限
*/
public void applyPermissions() {
try {
for (final PermissionModel model : mPermissionModels) {
if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(mActivity, model.permission)) {
ActivityCompat.requestPermissions(mActivity, new String[] { model.permission }, model.requestCode);
return;
}
}
if (mOnApplyPermissionListener != null) {
mOnApplyPermissionListener.onAfterApplyAllPermission();
}
} catch (Throwable e) {
Log.e(TAG, "", e);
}
}

/**
* 对应Activity的 {@code onRequestPermissionsResult(...)} 方法
*
* @param requestCode
* @param permissions
* @param grantResults
*/
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case READ_PHONE_STATE_CODE:
case WRITE_EXTERNAL_STORAGE_CODE:
// 如果用户不允许,我们视情况发起二次请求或者引导用户到应用页面手动打开
if (PackageManager.PERMISSION_GRANTED != grantResults[0]) {

// 二次请求,表现为:以前请求过这个权限,但是用户拒接了
// 在二次请求的时候,会有一个“不再提示的”checkbox
// 因此这里需要给用户解释一下我们为什么需要这个权限,否则用户可能会永久不在激活这个申请
// 方便用户理解我们为什么需要这个权限
if (ActivityCompat.shouldShowRequestPermissionRationale(mActivity, permissions[0])) {
AlertDialog.Builder builder =
new AlertDialog.Builder(mActivity).setTitle("权限申请").setMessage(findPermissionExplain(permissions[0]))
.setPositiveButton("确定", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
applyPermissions();
}
});
builder.setCancelable(false);
builder.show();
}
// 到这里就表示已经是第3+次请求,而且此时用户已经永久拒绝了,这个时候,我们引导用户到应用权限页面,让用户自己手动打开
else {
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity).setTitle("权限申请")
.setMessage("请在打开的窗口的权限中开启" + findPermissionName(permissions[0]) + "权限,以正常使用本应用")
.setPositiveButton("去设置", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
openApplicationSettings(REQUEST_OPEN_APPLICATION_SETTINGS_CODE);
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mActivity.finish();
}
});
builder.setCancelable(false);
builder.show();
}
return;
}

// 到这里就表示用户允许了本次请求,我们继续检查是否还有待申请的权限没有申请
if (isAllRequestedPermissionGranted()) {
if (mOnApplyPermissionListener != null) {
mOnApplyPermissionListener.onAfterApplyAllPermission();
}
} else {
applyPermissions();
}
break;
}
}

/**
* 对应Activity的 {@code onActivityResult(...)} 方法
*
* @param requestCode
* @param resultCode
* @param data
*/
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_OPEN_APPLICATION_SETTINGS_CODE:
if (isAllRequestedPermissionGranted()) {
if (mOnApplyPermissionListener != null) {
mOnApplyPermissionListener.onAfterApplyAllPermission();
}
} else {
mActivity.finish();
}
break;
}
}

/**
* 判断是否所有的权限都被授权了
*
* @return
*/
public boolean isAllRequestedPermissionGranted() {
for (PermissionModel model : mPermissionModels) {
if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(mActivity, model.permission)) {
return false;
}
}
return true;
}

/**
* 打开应用设置界面
*
* @param requestCode 请求码
*
* @return
*/
private boolean openApplicationSettings(int requestCode) {
try {
Intent intent =
new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + mActivity.getPackageName()));
intent.addCategory(Intent.CATEGORY_DEFAULT);

// Android L 之后Activity的启动模式发生了一些变化
// 如果用了下面的 Intent.FLAG_ACTIVITY_NEW_TASK ,并且是 startActivityForResult
// 那么会在打开新的activity的时候就会立即回调 onActivityResult
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mActivity.startActivityForResult(intent, requestCode);
return true;
} catch (Throwable e) {
Log.e(TAG, "", e);
}
return false;
}

/**
* 查找申请权限的解释短语
*
* @param permission 权限
*
* @return
*/
private String findPermissionExplain(String permission) {
if (mPermissionModels != null) {
for (PermissionModel model : mPermissionModels) {
if (model != null && model.permission != null && model.permission.equals(permission)) {
return model.explain;
}
}
}
return null;
}

/**
* 查找申请权限的名称
*
* @param permission 权限
*
* @return
*/
private String findPermissionName(String permission) {
if (mPermissionModels != null) {
for (PermissionModel model : mPermissionModels) {
if (model != null && model.permission != null && model.permission.equals(permission)) {
return model.name;
}
}
}
return null;
}

private static class PermissionModel {

/**
* 权限名称
*/
public String name;

/**
* 请求的权限
*/
public String permission;

/**
* 解析为什么请求这个权限
*/
public String explain;

/**
* 请求代码
*/
public int requestCode;

public PermissionModel(String name, String permission, String explain, int requestCode) {
this.name = name;
this.permission = permission;
this.explain = explain;
this.requestCode = requestCode;
}
}

/**
* 权限申请事件监听
*/
public interface OnApplyPermissionListener {

/**
* 申请所有权限之后的逻辑
*/
void onAfterApplyAllPermission();
}

}


工具类:每次用到新的都会来更新一下,或者忘记了也来看一下。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string