Android-工具类

Android-工具类

目录

Android-工具类

1.CustomUtils

2.DataUtils

3.ImageUtil

4.自定义Toast类

5.网络监听类

6.ProgressDialogUtil

7.StringUtil

8.SystemUtil

9.UIUtil

10. SP缓存数据,公共类


平时使用的一些简单的工具类。

1.CustomUtils

获得软件、设备分辨率信息、修改字体,获取日期,日期比较


import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.text.format.DateFormat;
import android.util.DisplayMetrics;

/**
 * @author M.xang
 * @时间 2019年10月23日
 * @描述 工具类-获得软件、设备分辨率信息、修改字体,日期
 */
public class CustomUtils {

	public static String getVersionInfo(Activity activity) {
		String Ver = "软件版本:" + getVersion(activity);
		Ver += '\n';
		Ver += "创建时间:" + DateFormat.format("yyyy-MM-dd", getApkUpdateTime(activity));
		Ver += '\n';
		Ver += getDisplay(activity);
		return Ver;
	}

	public static String getVersion(Context context) {// 获取版本号
		try {
			String name = context.getPackageName();
			PackageManager manager = context.getPackageManager();
			PackageInfo pi = manager.getPackageInfo(name, 0);
			return pi.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 查询手机内非系统应用
	 * 
	 * @param context
	 * @return
	 */
	public static List<PackageInfo> getAllApps(Context context) {
		List<PackageInfo> apps = new ArrayList<PackageInfo>();
		PackageManager pManager = context.getPackageManager();
		// 获取手机内所有应用
		List<PackageInfo> paklist = pManager.getInstalledPackages(0);

		for (int i = 0; i < paklist.size(); i++) {
			PackageInfo pak = (PackageInfo) paklist.get(i);
			// 判断是否为非系统预装的应用程序
			if ((pak.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
				// customs applications
				apps.add(pak);
			}
		}
		return apps;
	}
	/**
	 * // 获取版本号(内部识别号)
	 * @param context
	 * @return
	 */
	public static int getVersionCode(Context context) {
		try {
			PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return pi.versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return 0;
		}
	}
	/**
	 * 分辨率
	 * @param activity
	 * @return
	 */
	public static String getDisplay(Activity activity) {
		DisplayMetrics metric = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
		int width = metric.widthPixels; // 屏幕宽度(像素)
		int height = metric.heightPixels; // 屏幕高度(像素)
		float density = metric.density; // 屏幕密度(0.75 / 1.0 / 1.5)
		int densityDpi = metric.densityDpi; // 屏幕密度DPI(120 / 160 / 240)
		float scale = metric.scaledDensity;

		/*
		 * mdpi 120dpi~160dpi hdpi 160dpi~240dpi xhdpi 240dpi~320dpi xxhdpi
		 * 320dpi~480dpi xxxhdpi 480dpi~640dpi
		 */

		String dpi = "";
		if (densityDpi >= 120 && densityDpi < 160) {
			dpi = "mdpi";
		} else if (densityDpi >= 160 && densityDpi < 240) {
			dpi = "hdpi";
		} else if (densityDpi >= 240 && densityDpi < 320) {
			dpi = "xhdpi";
		} else if (densityDpi >= 320 && densityDpi < 480) {
			dpi = "xxhdpi";
		} else if (densityDpi >= 480 && densityDpi < 640) {
			dpi = "xxxhdpi";
		} else {
			dpi = "unknown";
		}
		String str = "[" + width + "*" + height + ",dens:" + density + ",scale:" + scale + "," + densityDpi
				+ "dpi," + dpi + "]";

		return str;
	}

	public static long getApkUpdateTime(Context context) {
		ZipFile zf = null;
		try {
			ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);
			zf = new ZipFile(ai.sourceDir);
			ZipEntry ze = zf.getEntry("META-INF/MANIFEST.MF");
			return ze.getTime();
		} catch (Exception e) {
		} finally {
			if (zf != null) {
				try {
					zf.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return 0;
	}

	/**
	 * 获取系统当前日期
	 * 
	 * @return yyMMdd(年月日)
	 */
	public static String getDate() {
		SimpleDateFormat sdf3 = new SimpleDateFormat("yyMMdd");
		long nowMills = System.currentTimeMillis();
		String nowTime = sdf3.format(nowMills);
		return nowTime;
	}

	/**
	 * 获取系统当前时间
	 * 
	 * @return HHmmss(时分秒)
	 */
	public static String getTime() {
		SimpleDateFormat sdf3 = new SimpleDateFormat("HHmmss");
		long nowMills = System.currentTimeMillis();
		String nowTime = sdf3.format(nowMills);
		return nowTime;
	}

	/**
	 ** 获取星期几
	 * 
	 * @return Stringint
	 */
	public static String getWeek() {
		Calendar cal = Calendar.getInstance();
		int i = cal.get(Calendar.DAY_OF_WEEK);
		switch (i) {
		case 1:
			return "07";
		case 2:
			return "01";
		case 3:
			return "02";
		case 4:
			return "03";
		case 5:
			return "04";
		case 6:
			return "05";
		case 7:
			return "06";
		default:
			return "";
		}
	}
	/**
	 ** 获取星期几(蓝牙与硬件通信)
	 * 
	 * @return Stringint
	 */
	public static String getWeekBTCMD() {
		Calendar cal = Calendar.getInstance();
		int i = cal.get(Calendar.DAY_OF_WEEK);
		switch (i) {
		case 1:
			return "00";
		case 2:
			return "01";
		case 3:
			return "02";
		case 4:
			return "03";
		case 5:
			return "04";
		case 6:
			return "05";
		case 7:
			return "06";
		default:
			return "";
		}
	}

	/**
	 ** 获取星期几
	 * 
	 * @return String
	 */
	public static String getWeek(String str) {
		if (str.equals("01")) {
			return "星期一";
		} else if (str.equals("02")) {
			return "星期二";
		} else if (str.equals("03")) {
			return "星期三";
		} else if (str.equals("04")) {
			return "星期四";
		} else if (str.equals("05")) {
			return "星期五";
		} else if (str.equals("06")) {
			return "星期六";
		} else if (str.equals("07")) {
			return "星期日";
		}
		return "";
	}

	/**
	 * 获取系统当前时间
	 * 
	 * @return yyyy-MM-dd
	 */
	public static String getCurrentTime() {
		SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
		long nowMills = System.currentTimeMillis();
		String nowTime = sdf3.format(nowMills);
		return nowTime;
	}

	/**
	 * 获取系统当天的时间
	 * 
	 * @return HH:mm:ss
	 */
	public static String getCurrentDayOfHours() {
		SimpleDateFormat sdf3 = new SimpleDateFormat("HH:mm:ss");
		long nowMills = System.currentTimeMillis();
		String nowTime = sdf3.format(nowMills);
		return nowTime;
	}

	/**
	 * 规范当前时间
	 * 
	 * @return yyyy-MM-dd
	 */
	public static String getFormatTime(String time) {
		String year = time.substring(0, 4);
		String month = time.substring(5, time.lastIndexOf("-"));
		if (month.length() < 2) {
			month = "0" + month;
		}
		String day = time.substring(time.lastIndexOf("-") + 1);
		return year + "-" + month + "-" + day;
	}

	/**
	 ** 规范时间格式
	 * 
	 * @param time yyMMddWWHHmmss
	 * @return [年,月,日,星期几,时,分,秒]
	 */
	public static String[] getFormatDateTime(String time) {
		int len = time.length() / 2;// 两位一截取
		String[] strs = new String[len];
		for (int i = 0; i < len; i++) {
			String str = time.substring(i * 2, i * 2 + 2);
			strs[i] = str;
		}
		return strs;
	}

	/**
	 ** 计算时间差,默认差为5mins
	 * 
	 * @param endTime 结束时间
	 * @return true:时差大于5mins,false:小于5mins
	 */
	public static boolean getTimeDifference(String time) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
		try {
			long starTime = System.currentTimeMillis();
			Date parse = dateFormat.parse(time);
			long diff = Math.abs(starTime - parse.getTime());// 毫秒差绝对值
//			long day = diff / (24 * 60 * 60 * 1000);
//			long hour = (diff / (60 * 60 * 1000) - day * 24);
//			long min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
//			long s = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
//			long ms = (diff - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000 - min * 60 * 1000 - s * 1000);
			long hour1 = diff / (60 * 60 * 1000);
			long min1 = ((diff / (60 * 1000)) - hour1 * 60);
			long s1 = (diff / 1000 - hour1 * 60 * 60 - min1 * 60);

			if (hour1 > 0 || (min1 - 5) > 0) {
				return true;
			} else if ((min1 - 5) == 0) {
				if (s1 > 0) {
					return true;
				}
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 计算时间差
	 * 
	 * @param starTime 开始时间
	 * @param endTime  结束时间
	 * @return 返回时间差(s)
	 */
	public static String getTimeDiff(String starTime, String endTime) {
		String timeString = "";
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date parse = dateFormat.parse(starTime);
			Date parse1 = dateFormat.parse(endTime);
			long diff = parse1.getTime() - parse.getTime();// 毫秒差
			timeString = setTimeString(diff);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return timeString;
	}

	private static String setTimeString(long diff) {
		String timeStr = "";
		long hour = diff / (60 * 60 * 1000);
		long min = ((diff / (60 * 1000)) - hour * 60);
		long s = (diff / 1000 - hour * 60 * 60 - min * 60);
		if (hour > 0 || min > 0 || s >= 0) {
			if (hour != 0) {
				timeStr = hour + "小时" + min + "分" + s + "秒";
				return timeStr;
			}
			if (min != 0) {
				timeStr = timeStr + min + "分" + s + "秒";
				return timeStr;
			}
			if (s >= 0) {
				timeStr = s + "秒";
				return timeStr;
			}
		}
		return timeStr;
	}

}

2.DataUtils

数据转换



import java.util.Locale;

/**
 * @author M.xang
 * @时间 2019年2月19日
 * @描述 数据转换工具类
 */
public class DataUtils {

	/**
	 * 按照16进制的方式打印byte数组
	 * 
	 * @param b 需要打印的数组
	 */
	public static void printByteInHex(byte[] b) {
		if (b == null || b.length == 0) {
			return;
		} else {
			for (int i = 0; i < b.length; i++) {
				String sdata = Integer.toHexString(0xff & b[i]).toUpperCase(Locale.CHINA);
				if (sdata.length() == 1) {// 补足高位的0
					sdata = '0' + sdata;
				}
				System.out.print(sdata + ",");
			}
			System.out.println();
		}
	}

	/**
	 * 转换byte数组为16进制数的字符串
	 * 
	 * @param b 需要打印的数组
	 * @return 转换以后的字符串数组
	 */
	public static String getByteInHexString(byte[] b) {
		if (b == null || b.length == 0) {
			return "";
		} else {
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < b.length; i++) {
				String sdata = Integer.toHexString(0xff & b[i]).toUpperCase(Locale.CHINA);
				if (sdata.length() == 1) {// 补足高位的0
					sdata = '0' + sdata;
				}
				sb.append(sdata);
			}
			return sb.toString();
		}
	}

	/**
	 * 按照16进制的方式转换byte为字符串
	 * 
	 * @param b 需要打印的数组
	 * @return 转换以后的字符串数组
	 */
	public static String getByteInHexString(byte b) {
		StringBuffer sb = new StringBuffer();
		String sdata = Integer.toHexString(0xff & b).toUpperCase(Locale.CHINA);
		if (sdata.length() == 1) {// 补足高位的0
			sdata = '0' + sdata;
		}
		sb.append(sdata);
		return sb.toString();
	}

	/**
	 * 按照16进制的方式转换byte数组为字符串
	 * 
	 * @param b 需要打印的数组
	 * @return 转换以后的字符串数组
	 */
	public static String getByteHexString(byte[] b) {
		if (b == null || b.length == 0) {
			return "";
		} else {
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < b.length; i++) {
				String sdata = Integer.toHexString(0xff & b[i]).toUpperCase(Locale.CHINA);
				if (sdata.length() == 1) {// 如果是个位数,前面补0
					sdata = "0" + sdata;
				}
				sb.append(sdata);
			}
			return sb.toString();
		}
	}

	/**
	 * 按照16进制的方式打印byte数组,具有0x
	 * 
	 * @param b 需要打印的数组
	 */
	public static void printByteInHexHas0x(byte[] b) {
		if (b == null || b.length == 0) {
			return;
		} else {
			for (int i = 0; i < b.length; i++) {
				String sdata = Integer.toHexString(0xff & b[i]).toUpperCase(Locale.CHINA);
				if (sdata.length() == 1) {// 补足高位的0
					sdata = '0' + sdata;
				}
				System.out.print("0x" + sdata + ",");
			}
			System.out.println();
		}
	}

	/**
	 * 十六进制String转换为十进制String
	 * 
	 * @param hexStr
	 * @return
	 */
	public static String hexString2String(String hexStr) {
		byte[] hexByte = hexString2Bytes(hexStr);// 十六进制字符串,转成十进制int
		String r = "";
		for (int i = 0; i < hexByte.length; i++) {
			r = r + hexByte[i];
		}
		return r;
	}

	/**
	 * 16进制字符串转字节数组
	 */
	public static byte[] hexString2Bytes(String hex) {
		if ((hex == null) || (hex.equals(""))) {
			return null;
		} else {
			hex = hex.toUpperCase();
			byte[] b;
			if (hex.length() == 1) {
				b = new byte[1];
				char[] hc = hex.toCharArray();
				b[0] = (byte) charToByte(hc[0]);
			} else {
				int len = hex.length() / 2;
				b = new byte[len];
				char[] hc = hex.toCharArray();
				for (int i = 0; i < len; i++) {
					int p = 2 * i;
					b[i] = (byte) (charToByte(hc[p]) << 4 | charToByte(hc[p + 1]));
				}
			}
			return b;
		}
	}

	/*
	 * 字符转换为字节
	 */
	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}

	/**
	 * 将多个字节数组按顺序合并
	 * 
	 * @param data
	 * @return
	 */
	public static byte[] byteArraysToBytes(byte[][] data) {
		int length = 0;
		for (int i = 0; i < data.length; i++)
			length += data[i].length;
		byte[] send = new byte[length];
		int k = 0;
		for (int i = 0; i < data.length; i++)
			for (int j = 0; j < data[i].length; j++)
				send[k++] = data[i][j];
		return send;
	}
	
	/**
	 * 十六进制数字,转换为十进制数字
	 * @param hex
	 * @return
	 */
	public static int hexToInt(String hexStr) {
		int value = 0;
		byte[] hexByte = hexString2Bytes(hexStr);
		if (hexByte.length == 2) {
			int b1 = (hexByte[0] & 0xFF) << 8;
			int b2 = hexByte[1] & 0xFF;
			value = b1 + b2;
		} else if (hexByte.length == 1) {
			value = hexByte[0] & 0xFF;
		}
		return value;
	}
}

3.ImageUtil

图片处理工具类


import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.media.ExifInterface;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Base64;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author ${M.xang} 创建时间:2018-5-10 上午9:45:02 类描述 : 图片处理工具类
 */
public class ImageUtils {

	private static Bitmap bmp;

	public static Bitmap Bytes2Bimap(byte[] b) {
		if (b.length != 0) {
			return BitmapFactory.decodeByteArray(b, 0, b.length);
		} else {
			return null;
		}
	}

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

	public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {

			final int halfHeight = height / 2;
			final int halfWidth = width / 2;
			while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
				inSampleSize *= 2;
			}
		}
		return inSampleSize;
	}

	// Get Path Image file
	public final static String getRealPathFromURI(Context context, Uri contentUri) {
		Cursor cursor = null;
		try {
			String[] proj = { MediaStore.Images.Media.DATA };
			cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
			int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}
	}

	/**
	 * 旋转照片
	 * 
	 * @param b
	 * @param degrees 旋转角度
	 * @return
	 */
	public final static Bitmap rotate(Bitmap b, float degrees) {
		if (degrees != 0 && b != null) {
			Matrix m = new Matrix();
			m.setRotate(degrees, (float) b.getWidth() / 2, (float) b.getHeight() / 2);
			Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), m, true);
			if (b != b2) {
				b.recycle();
				b = b2;
			}
		}
		return b;
	}

	public static Bitmap getBitmap(String filePath) {
		Bitmap bitmap = BitmapFactory.decodeFile(filePath);
		if (bitmap != null) {
			try {
				ExifInterface ei = new ExifInterface(filePath);
				int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
						ExifInterface.ORIENTATION_NORMAL);
				switch (orientation) {
				case ExifInterface.ORIENTATION_ROTATE_90:
					bitmap = ImageUtils.rotate(bitmap, 90);
					break;
				case ExifInterface.ORIENTATION_ROTATE_180:
					bitmap = ImageUtils.rotate(bitmap, 180);
					break;
				case ExifInterface.ORIENTATION_ROTATE_270:
					bitmap = ImageUtils.rotate(bitmap, 270);
					break;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return bitmap;
	}

	public static Bitmap getBitmap(String filePath, int width, int height) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, options);
		options.inSampleSize = calculateInSampleSize(options, width, height);
		options.inJustDecodeBounds = false;
		options.inPreferredConfig = Bitmap.Config.RGB_565;
		Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
		if (bitmap != null) {
			try {
				ExifInterface ei = new ExifInterface(filePath);
				int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
						ExifInterface.ORIENTATION_NORMAL);
				switch (orientation) {
				case ExifInterface.ORIENTATION_ROTATE_90:
					bitmap = ImageUtils.rotate(bitmap, 90);
					break;
				case ExifInterface.ORIENTATION_ROTATE_180:
					bitmap = ImageUtils.rotate(bitmap, 180);
					break;
				case ExifInterface.ORIENTATION_ROTATE_270:
					bitmap = ImageUtils.rotate(bitmap, 270);
					break;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return bitmap;
	}

	public static Bitmap cropBitmap(Bitmap bitmap, Rect rect) {
		int w = rect.right - rect.left;
		int h = rect.bottom - rect.top;
		Bitmap ret = Bitmap.createBitmap(w, h, bitmap.getConfig());
		Canvas canvas = new Canvas(ret);
		canvas.drawBitmap(bitmap, -rect.left, -rect.top, null);
		bitmap.recycle();
		return ret;
	}

	public static Bitmap get(Bitmap bitmap, int rotate) {
		Bitmap.Config config = Bitmap.Config.RGB_565;
		if (bitmap.getConfig() != null)
			config = bitmap.getConfig();
		bmp = bitmap.copy(config, true);
		switch (rotate) {
		case 90:
			bmp = rotate(bmp, 90);
			break;
		case 180:
			bmp = rotate(bmp, 180);
			break;
		case 270:
			bmp = rotate(bmp, 270);
			break;
		}
		bitmap.recycle();
		return bmp;
	}

	/**
	 * Base64-将bitmap的byte[]转化为String
	 * 
	 * @param mImage
	 * @return
	 */
	public static String getPhotoStr64(byte[] mImage) {
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int count = mImage.length;
			baos.write(mImage, 0, count);
			String uploadBuffer = new String(Base64.encode(baos.toByteArray(), baos.size())); // 进行Base64编码
			return uploadBuffer;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * Base64-将String转换为bitmap
	 * 
	 * @param string
	 * @return
	 */
	public static Bitmap stringtoBitmap(String string) {
		// 将字符串转换成Bitmap类型
		Bitmap bitmap = null;
		try {
			byte[] bitmapArray;
			bitmapArray = Base64.decode(string, Base64.DEFAULT);
			bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bitmap;
	}

	/**
	 ** 文件转Base64
	 * @param filePath
	 * @return
	 */
	public static String file2Base64(String filePath) {
		// decode to bitmap
		Bitmap bitmap = BitmapFactory.decodeFile(filePath);
		// convert to byte array
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.PNG, 80, baos);
		byte[] bytes = baos.toByteArray();
		// base64 encode
		byte[] encode = Base64.encode(bytes, Base64.DEFAULT);
		String encodeString = new String(encode);
		return encodeString;
//		FileInputStream objFileIS = null;
//		try {
//			objFileIS = new FileInputStream(filePath);
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		}
//		ByteArrayOutputStream objByteArrayOS = new ByteArrayOutputStream();
//		byte[] byteBufferString = new byte[1024];
//		try {
//			for (int readNum; (readNum = objFileIS.read(byteBufferString)) != -1;) {
//				objByteArrayOS.write(byteBufferString, 0, readNum);
//			}
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		String videodata = Base64.encodeToString(objByteArrayOS.toByteArray(), Base64.DEFAULT);
//		return videodata;
	}
	
	/**
	 * 保存照片
	 * 
	 * @param bitmap
	 * @param file
	 */
	public static void saveBitmapFile(Bitmap bitmap, File file) {
		try {
			if (bitmap == null) {
				return;
			}
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
			bos.flush();
			bos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除照片
	 * 
	 * @param path 图片路径
	 * @param name 图片名称
	 */
	public static void deleteImage(String path, String name) {
		File filePath = new File(path);
		if (filePath.exists()) {
			File file = new File(path, name);
			file.delete();
		}
	}

}

4.自定义Toast类


import android.content.Context;
import android.widget.Toast;
/**
 * 自定义Toast类
 * @author mx
 *
 */
public class MyToast {

	private static Toast mToast;
	/**
	 * Toast显示方法
	 * @param context
	 * @param text
	 */
	public static void showToast(Context context, String text) {
		if (mToast == null) {
			mToast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
		} else {
			mToast.setText(text);
			mToast.setDuration(Toast.LENGTH_SHORT);
		}
		mToast.show();
	}
	/**
	 * 关闭Toast调用方法
	 */
	public static void cancelToast() {
		if (mToast != null) {
			mToast.cancel();
		}
	}

}

5.网络监听类

NetEvevt接口:监听网络变化,在相应的Activity中进行实现。

在initData中实例:



import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
 * @author ${M.xang}
 * 创建时间:2018-8-7 上午11:55:19 
 * 类描述 :
 *		网络监听
 */
public class NetUtil extends BroadcastReceiver {

	public NetEvevt evevt = MainActivity.evevt;
	/**
	 * 没有连接网络
	 */
	private static final int NETWORK_NONE = -1;
	/**
	 * 移动网络
	 */
	private static final int NETWORK_MOBILE = 0;
	/**
	 * 无线网络
	 */
	private static final int NETWORK_WIFI = 1;

	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
			int netWorkState = getNetWorkState(context);
			if (netWorkState == 1 || netWorkState == 0) {// 无线网,移动网
				evevt.onNetChange(1);// WiFi连接了
			} else if (netWorkState == -1) {// 没有网时,将WiFi名字保存为空
				evevt.onNetChange(-1);// WiFi连接了
			}
		}
	}
	
	public static int getNetWorkState(Context context) {
		// 得到连接管理器对象
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();
		if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
			if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_WIFI)) {
				return NETWORK_WIFI;
			} else if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_MOBILE)) {
				return NETWORK_MOBILE;
			}
		} else {
			return NETWORK_NONE;
		}
		return NETWORK_NONE;
	}

	/**
	 * @author ${M.xang}
	 * 创建时间:2018-8-7 上午11:55:37 
	 * 类描述 :
	 *		网络监听的回调	<在调用的类中实现>
	 */
	public interface NetEvevt {
		/**
		 * @param netMobile 0:没有网络;1:移动网络;3:WIFI
		 */
		public void onNetChange(int netMobile);
	}

}

6.ProgressDialogUtil

全局加载的dialog



import android.app.AlertDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

/**
 * @author M.xang
 * @时间 2019年6月24日
 * @描述 全局加载的dialog
 */
public class ProgressDialogUtil {

	private static AlertDialog dialog = null;
	private static TextView title = null;
	private static Context mcontext = null;
	private static final int START_DIALOG = 0;// 开始对话框
	private static final int UPDATE_DIALOG = 1;// 更新对话框
	private static final int STOP_DIALOG = 2;// 销毁对话框

	private static Handler handler = new Handler(Looper.getMainLooper()) {
		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			String message = "";
			switch (msg.what) {
			case START_DIALOG:// 开始对话框
				message = (String) msg.obj;
				if (dialog != null) {
					stopLoad();
					startLoad(mcontext, message);
					return;
				}
				init(message);
			case UPDATE_DIALOG:// 更新对话框
				message = (String) msg.obj;
				if (title.VISIBLE == View.VISIBLE) {
					if (StringUtil.isEmpty(message)) {
						title.setVisibility(View.GONE);
					} else {
						title.setText(message);
					}
				} else {
					if (!StringUtil.isEmpty(message)) {
						title.setText(message);
						title.setVisibility(View.VISIBLE);
					}
				}
				break;
			case STOP_DIALOG:// 销毁对话框
				if (dialog != null) {
					dialog.dismiss();
					dialog.cancel();
					dialog = null;
					title = null;
				}
				break;
			default:
				break;
			}
		}
	};

	/**
	 * @方法说明:启动对话框
	 * @方法名称:startLoad
	 * @param con   上下文
	 * @param msg   提示内容
	 * @param state 0:点击返回不能取消,1:点击返回可以取消
	 * @返回值:void
	 */
	public static void startLoad(Context context, String msg) {
		mcontext = context;
		if (mcontext == null) {
			return;
		}
		if (SystemUtil.isBackground(mcontext)) {// 如果程序在后台,则不加载
			return;
		}
		Message mssage = new Message();
		mssage.what = START_DIALOG;
		mssage.obj = msg;
		handler.sendMessage(mssage);// 创建dialog
	}

	/**
	 * @方法说明:更新显示的内容
	 * @方法名称:UpdateMsg
	 * @param msg
	 * @返回值:void
	 */
	public static void UpdateMsg(String msg) {
		Message message = new Message();
		message.what = UPDATE_DIALOG;
		message.obj = msg;
		handler.sendMessage(message);// 更新文字内容
	}

	/**
	 * @方法说明:让警告框消失
	 * @方法名称:dismiss
	 * @返回值:void
	 */
	public static void stopLoad() {
		handler.sendEmptyMessage(STOP_DIALOG);// 隐藏diaolog
	}

	/**
	 * @方法说明:加载控件与布局
	 * @方法名称:init
	 * @返回值:void
	 */
	private static void init(String mssg) {
		if (SystemUtil.isBackground(mcontext)) {
			// 如果程序在后台,则不加载
			return;
		}
		if (null != mcontext) {
			LayoutInflater flat = LayoutInflater.from(mcontext);
			View v = flat.inflate(R.layout.view_progressdialog, null);
			// v.setBackgroundColor(context.getResources().getColor(android.R.color.transparent));
			// 创建对话
			dialog = new AlertDialog.Builder(mcontext, R.style.dialog).create();
			// 设置点击返回框外边不消失
			dialog.setCanceledOnTouchOutside(false);
			// 给该对话框增加系统权限
			// dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
			// 显示对话
			dialog.show();
			// 加载控件
			title = (TextView) v.findViewById(R.id.loading_title);
			if (StringUtil.isEmpty(mssg)) {
				title.setVisibility(View.GONE);
			} else {
				title.setVisibility(View.VISIBLE);
				title.setText(mssg);
			}
			// 必须放到显示对话框下面,否则显示不出效果
			Window window = dialog.getWindow();
			// window.getAttributes().x = 0;
			// window.getAttributes().y = 0;// 设置y坐标
			WindowManager.LayoutParams params = window.getAttributes();
			params.width = ViewGroup.LayoutParams.WRAP_CONTENT;
			params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
			params.gravity = Gravity.CENTER;
			// params.alpha = 0.6f;
			window.setAttributes(params);// 加载布局组件
			dialog.getWindow().setContentView(v);
		}
	}
}

7.StringUtil

字符串操作工具类


import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author M.xang
 * @时间 2018年11月26日
 * @描述 字符串操作工具类
 */
public class StringUtil {

	/**
	 * 判断字符串是否只包含数字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumer(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		return pattern.matcher(str).matches();
	}
	/**
	 * 判断字符串是否是大写的数字 一二三...
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isDXNumer(String str) {
		if ("一二三四五六七八九十".contains(str)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 判断字符串是否为null || 空 || "null",是则返回true
	 * 
	 * @param string
	 * @return
	 */
	public static boolean isEmpty(String string) {
		if (string == null || string.equals("") || string.equals("null")) {
			return true;
		}
		return false;
	}

	/**
	 * 四舍五入保留两位小数
	 * 
	 * @param double
	 * @return
	 */
	public static String getFormat(double d) {
		DecimalFormat df = new DecimalFormat(".##");
		String st = df.format(d);
		return st;
	}

	/**
	 * 将详细地址中 楼号-单元号-层数-户号改为多位数,不足前面补0
	 * 
	 * @param String 详细地址
	 * @return
	 */
	public static String getAddress(String allAddress) {
		String address = "";
		if (isEmpty(allAddress)) {
			return address;
		}
		// 岳麓-南山雍江汇6栋1单元201号
		// 瑞达路97号6号楼3单元65号
		// 开发区劳动小区14栋501
		// 郑州市高新区金梭路32号鸿森创业大厦B座1208号
		// 郑州市高新区金梭路32号鸿森大厦C座3-602号
		// 获取 楼号-单元号-层数-户号
		// 号楼、栋、幢、、单元号
		List<String> listStr = new ArrayList<String>();
		String string = "";
		String numStr = "";
		int isNumber = -1;
		for (int i = 0; i < allAddress.length(); i++) {
			String s = allAddress.charAt(i) + "";
			String s2 = "";
			if (i == allAddress.length() - 1) {
				s2 = "";
			} else {
				s2 = allAddress.charAt(i + 1) + "";
			}
			if (isNumer(s)) {// 是数字
				numStr = numStr + s;
				isNumber = 0;
			} else if (isDXNumer(s)) {// 大写数字
				numStr = numStr + s;
				isNumber = 1;
			} else {// 不是数字
				if (isNumber != -1) {
					if (isNumber == 0) {
						while (numStr.length() <= 4) {
							numStr = "0" + numStr;
						}
					}
					numStr = numStr + s;
					if (isNumer(s2) || isDXNumer(s2)) {
						listStr.add(numStr);
						numStr = "";
					}
				} else {
					string = string + s;
				}
			}
		}
		
		for (int i = 0; i < listStr.size(); i++) {
			String num = listStr.get(i);
			address = address + num;
		}
		address = string + address;
		return address;
	}

}

8.SystemUtil

系统工具类,隐藏键盘之类的


import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;

/**
 * 
 * @author ${M.xang} 创建时间:2018-3-19 上午10:25:44 类描述 : 系统工具类,隐藏键盘之类的
 */
public class SystemUtil {

	private static SystemUtil systemUtil;

	public SystemUtil() {

	}

	/** 获取SystemUtil实例 ,单例模式 */
	public static SystemUtil getInstance() {
		if (systemUtil == null) {
			systemUtil = new SystemUtil();
		}
		return systemUtil;
	}

	/**
	 * 隐藏软件盘
	 */
	public void hideSoftKey(Activity activity) {
		// 隐藏软键盘
		if (activity.getWindow()
				.getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
			activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		}
	}

	public void doubleClickExit(int keyCode, KeyEvent event) {

	}

	/**
	 * 设置图片控件闪烁
	 * 
	 * @param iv_chat_head
	 */
	public void setFlickerAnimation(ImageView iv_chat_head) {
		final Animation animation = new AlphaAnimation(1, 0);
		animation.setDuration(500);// 闪烁时间间隔
		animation.setInterpolator(new AccelerateDecelerateInterpolator());
		animation.setRepeatCount(Animation.INFINITE);
		animation.setRepeatMode(Animation.REVERSE);
		iv_chat_head.setAnimation(animation);
	}

	/**
	 * 获取本机IP
	 * 
	 * @param context
	 * @return
	 */
	public String getIP(Context context) {
		NetworkInfo info = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE))
				.getActiveNetworkInfo();
		if (info != null && info.isConnected()) {
			if (info.getType() == ConnectivityManager.TYPE_MOBILE) {// 当前使用2G/3G/4G网络
				try {
					// Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
					for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
							.hasMoreElements();) {
						NetworkInterface intf = en.nextElement();
						for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
								.hasMoreElements();) {
							InetAddress inetAddress = enumIpAddr.nextElement();
							if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
								return inetAddress.getHostAddress();
							}
						}
					}
				} catch (SocketException e) {
					e.printStackTrace();
				}
			} else if (info.getType() == ConnectivityManager.TYPE_WIFI) {// 当前使用无线网络
				WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
				WifiInfo wifiInfo = wifiManager.getConnectionInfo();
				int ip = wifiInfo.getIpAddress();
				String ipAddress = intIP2StringIP(ip);// 得到IPV4地址
				return ipAddress;
			}
		} else {
			// 当前无网络连接,请在设置中打开网络
		}
		return null;
	}

	/**
	 * 将得到的int类型的IP转换为String类型
	 * 
	 * @param ip
	 * @return
	 */
	public String intIP2StringIP(int ip) {
		return (ip & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + (ip >> 24 & 0xFF);
	}

	/**
	 * 规范IP格式
	 * 
	 * @param ip 172.30.204.2
	 * @return 返回为{172,030,204,002}
	 */
	public String formatIP(String ip) {
		String str = "";
		String[] IPs = new String[4];
		IPs = ip.split("\\.");
		for (int i = 0; i < IPs.length; i++) {
			String s = IPs[i];
			while (s.length() < 3) {
				s = "0" + s;
				IPs[i] = s;
			}
			str += s;
		}
		return str;
	}

	/**
	 * 根据wifi信息获取本地mac(6.0以下)
	 * 
	 * @param context
	 * @return
	 */
	public static String getMac(Context context) {
		// 6.0以下
		WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		WifiInfo winfo = wifi.getConnectionInfo();
		String mac = winfo.getMacAddress();
		return mac;
	}
	
	/**
	 * @方法说明:判断当前应用程序是否后台运行
	 * @方法名称:isBackground
	 * @param context
	 * @return
	 * @返回值:boolean
	 */
	public static boolean isBackground(Context context) {
		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
		for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
			if (appProcess.processName.equals(context.getPackageName())) {
				if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
					// 后台运行
					return true;
				} else {
					// 前台运行
					return false;
				}
			}
		}
		return false;
	}
}

9.UIUtil

UI实例化工具


import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

/**
 * @author ${M.xang} 创建时间:2018-10-26 上午11:16:16 类描述 : 控制界面展示的工具类
 */
public class UIUtil {

	/**
	 * 初始化控件的泛型写法
	 * 
	 * @param activity 当前所在activity
	 * @param id       要初始化的id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <E extends View> E findView(Activity activity, int id) {
		try {
			return (E) activity.getWindow().getDecorView().findViewById(id);
		} catch (ClassCastException e) {
			throw e;
		}
	}

	/**
	 * 初始化控件的泛型写法
	 * 
	 * @param view 当前所在view
	 * @param id   要初始化的id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <E extends View> E findView(View view, int id) {
		try {
			return (E) view.findViewById(id);
		} catch (ClassCastException e) {
			throw e;
		}
	}

	/**
	 * 设置状态栏背景色: 4.4以下不处理,4.4使用默认沉浸式状态栏,android5.0及以上才有透明效果
	 * 
	 * @param color
	 */
	public static void setBarColor(Activity activity, int color) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			Window win = activity.getWindow();
			win.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);// 沉浸式状态栏
//            View decorView = win.getDecorView();
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//android5.0及以上才有透明效果
//                win.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);//清除flag
//                //让应用的主体内容占用系统状态栏的空间
//                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
//                decorView.setSystemUiVisibility(decorView.getSystemUiVisibility() | option);
//                win.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//                win.setStatusBarColor(color);//设置状态栏背景色
//            }
		}
	}

	/**
	 ** 获取项目中drawable
	 * 
	 * @param context
	 * @return
	 */
	public static Drawable getResouceDrawableValue(Context context, int idValue) {
		return context.getResources().getDrawable(idValue);
	}

	/**
	 ** 获取项目中color的int值
	 * 
	 * @param context
	 * @return
	 */
	public static int getResouceColorValue(Context context, int idValue) {
		return context.getResources().getColor(idValue);
	}
}

10. SP缓存数据,公共类

PreferencesUtils、SPUtil



/**
 * @author ${M.xang} 创建时间:2018-5-15 上午8:55:53 类描述 : SP缓存调用方法
 */
public class SPUtil {
	// 服务器IP
	public static String getIP() {
		return PreferencesUtils.getString(MyApplication.getContextObject(), "IP", "");
	}

	public static void setIP(String ip) {
		PreferencesUtils.putString(MyApplication.getContextObject(), "IP", ip);
	}

	public static int getPort() {
		return PreferencesUtils.getInt(MyApplication.getContextObject(), "PORT", 80);
	}

	public static void setPort(int port) {
		PreferencesUtils.putInt(MyApplication.getContextObject(), "PORT", port);
	}

	

}

import android.content.Context;
import android.content.SharedPreferences;

import java.util.Map;

/**
 * @author ${M.xang} 创建时间:2018-5-15 上午8:53:56 类描述 : SP缓存数据,公共类
 */
public class PreferencesUtils {

	public static String PREFERENCE_NAME = "LocalInfo";

	public static boolean putString(Context context, String key, String value) {
		SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString(key, value);
		return editor.commit();
	}

	public static String getString(Context context, String key) {
		return getString(context, key, null);
	}

	public static String getString(Context context, String key, String defaultValue) {
		SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
		return settings.getString(key, defaultValue);
	}

	public static boolean putInt(Context context, String key, int value) {
		SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putInt(key, value);
		return editor.commit();
	}

	public static int getInt(Context context, String key) {
		return getInt(context, key, -1);
	}

	public static int getInt(Context context, String key, int defaultValue) {
		SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
		return settings.getInt(key, defaultValue);
	}

	public static boolean putLong(Context context, String key, long value) {
		SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putLong(key, value);
		return editor.commit();
	}

	public static long getLong(Context context, String key) {
		return getLong(context, key, -1);
	}

	public static long getLong(Context context, String key, long defaultValue) {
		SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
		return settings.getLong(key, defaultValue);
	}

	public static boolean putFloat(Context context, String key, float value) {
		SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putFloat(key, value);
		return editor.commit();
	}

	public static float getFloat(Context context, String key) {
		return getFloat(context, key, -1);
	}

	public static float getFloat(Context context, String key, float defaultValue) {
		SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
		return settings.getFloat(key, defaultValue);
	}

	public static boolean putBoolean(Context context, String key, boolean value) {
		SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putBoolean(key, value);
		return editor.commit();
	}

	public static boolean getBoolean(Context context, String key) {
		return getBoolean(context, key, false);
	}

	public static boolean getBoolean(Context context, String key, boolean defaultValue) {
		SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
		return settings.getBoolean(key, defaultValue);
	}

	public static void cleanSp(Context context) {
		SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		Map<String, ?> map = settings.getAll();
		for (Map.Entry<String, ?> entry : map.entrySet()) {
			if (!entry.getKey().equals("tmh") && !entry.getKey().equals("UserName")
					&& !entry.getKey().equals("PassWorld")) {
				editor.remove(entry.getKey());//清除相应的SP缓存
			}
		}
		editor.commit();
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值