android开发常用工具类集合

文档总览:

1.网略无线相关

2.LogCat相关

3.Toast相关

3.Dialog相关

4.文件操作相关

5.Md5相关

6.字符验证相关

7.SdCard相关

8.App操作相关

9.SharedPreferences相关

10.app版本相关

11:杂乱的收集

网络无线相关:

判断手机是否连接网络:
public static boolean isOnline(Context context) {
boolean flag = false;
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();


if (mNetworkInfo != null) {
mNetworkInfo.isAvailable();
flag = true;
} else {
flag = false;
}
}
return flag;
}
判断手机连接的是哪种网络
public static int getWlanState(Context context) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean wifi = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
boolean gprs = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
if (gprs) {
return 1;// GPRS网
} else if (wifi) {
return 2;// WIFI网
} else {
return 0;// 无网
}
}
判断手机是否开启GPS
public static boolean isGPS(Context context) {
// 通过GPS卫星定位,定位级别可以精确到街
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// 通过WLAN或移动网络(3G/2G)确定的位置(也称作AGPS,辅助GPS定位。主要用于在室内或遮盖物(建筑群或茂密的深林等)密集的地方定位)
// boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (gps) {
return true;
} else {
return false;
}
}
打开系统网络设置界面
public static boolean openSttingForWlan(Context context) {
Intent intent = null;
// 判断手机系统的版本 即API大于10 就是3.0或以上版本
if (android.os.Build.VERSION.SDK_INT > 10) {
intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
} else {
intent = new Intent();
ComponentName component = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
intent.setComponent(component);
intent.setAction("android.intent.action.VIEW");
}
context.startActivity(intent);


return true;
}
打开系统GPS设置界面
public static boolean openSttingForGPS(Context context) {
boolean flagSetting = false;
Intent intent = new Intent();
intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(intent);


} catch (ActivityNotFoundException ex) {


intent.setAction(Settings.ACTION_SETTINGS);
try {
context.startActivity(intent);
flagSetting = true;
} catch (Exception e) {
flagSetting = false;
}
}
return flagSetting;
}
尝试帮用户直接开启GPS
@SuppressWarnings("deprecation")
public static void openGPS(Context context) {
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
context.sendBroadcast(intent);
String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains("gps")) { // if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
context.sendBroadcast(poke);
}


}

LogCat统一管理:

<span style="font-size:18px;">public class L
{

	private L()
	{
		/* cannot be instantiated */
		throw new UnsupportedOperationException("cannot be instantiated");
	}

	public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化
	private static final String TAG = "way";

	// 下面四个是默认tag的函数
	public static void i(String msg)
	{
		if (isDebug)
			Log.i(TAG, msg);
	}

	public static void d(String msg)
	{
		if (isDebug)
			Log.d(TAG, msg);
	}

	public static void e(String msg)
	{
		if (isDebug)
			Log.e(TAG, msg);
	}

	public static void v(String msg)
	{
		if (isDebug)
			Log.v(TAG, msg);
	}

	// 下面是传入自定义tag的函数
	public static void i(String tag, String msg)
	{
		if (isDebug)
			Log.i(tag, msg);
	}

	public static void d(String tag, String msg)
	{
		if (isDebug)
			Log.i(tag, msg);
	}

	public static void e(String tag, String msg)
	{
		if (isDebug)
			Log.i(tag, msg);
	}

	public static void v(String tag, String msg)
	{
		if (isDebug)
			Log.i(tag, msg);
	}
}</span>
Toast统一管理:

<span style="font-size:18px;">public class T
{

	private T()
	{
		/* cannot be instantiated */
		throw new UnsupportedOperationException("cannot be instantiated");
	}

	public static boolean isShow = true;

	/**
	 * 短时间显示Toast
	 * 
	 * @param context
	 * @param message
	 */
	public static void showShort(Context context, CharSequence message)
	{
		if (isShow)
			Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 短时间显示Toast
	 * 
	 * @param context
	 * @param message
	 */
	public static void showShort(Context context, int message)
	{
		if (isShow)
			Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 长时间显示Toast
	 * 
	 * @param context
	 * @param message
	 */
	public static void showLong(Context context, CharSequence message)
	{
		if (isShow)
			Toast.makeText(context, message, Toast.LENGTH_LONG).show();
	}

	/**
	 * 长时间显示Toast
	 * 
	 * @param context
	 * @param message
	 */
	public static void showLong(Context context, int message)
	{
		if (isShow)
			Toast.makeText(context, message, Toast.LENGTH_LONG).show();
	}

	/**
	 * 自定义显示Toast时间
	 * 
	 * @param context
	 * @param message
	 * @param duration
	 */
	public static void show(Context context, CharSequence message, int duration)
	{
		if (isShow)
			Toast.makeText(context, message, duration).show();
	}

	/**
	 * 自定义显示Toast时间
	 * 
	 * @param context
	 * @param message
	 * @param duration
	 */
	public static void show(Context context, int message, int duration)
	{
		if (isShow)
			Toast.makeText(context, message, duration).show();
	}</span>
Dialog管理:

<span style="font-size:18px;">public class DialogTool
{
	public static final int NO_ICON = -1; // 无图标
	/**
	 * @description 创建消息对话框
	 * 
	 * @param context
	 *            上下文 必填
	 * @param iconId
	 *            图标,如:R.drawable.icon 或 DialogTool.NO_ICON 必填
	 * @param title
	 *            标题 必填
	 * @param message
	 *            显示内容 必填
	 * @param btnName
	 *            按钮名称 必填
	 * @param listener
	 *            监听器,需实现android.content.DialogInterface.OnClickListener接口 必填
	 * @return
	 */
	@SuppressLint("NewApi")
	public static Dialog createMessageDialog(Context context, String title,
			String message, String btnName, OnClickListener listener,
			int iconId, boolean flag)
	{
		Dialog dialog = null;
		AlertDialog.Builder builder = new AlertDialog.Builder(context,
				AlertDialog.THEME_HOLO_LIGHT);

		if (iconId != NO_ICON)
		{
			// 设置对话框图标
			builder.setIcon(iconId);
		}
		// 设置对话框标题
		builder.setTitle(title);
		// 设置对话框消息
		builder.setMessage(message);
		// 设置按钮
		builder.setPositiveButton(btnName, listener);
		// 创建一个消息对话框
		dialog = builder.create();
		// 点击其它地方可以让窗口消失
		dialog.setCancelable(flag);

		return dialog;
	}

	/**
	 * @description 创建警示(确认、取消)对话框
	 * 
	 * @param context
	 *            上下文 必填
	 * @param iconId
	 *            图标,如:R.drawable.icon 或 DialogTool.NO_ICON 必填
	 * @param title
	 *            标题 必填
	 * @param message
	 *            显示内容 必填
	 * @param positiveBtnName
	 *            确定按钮名称 必填
	 * @param negativeBtnName
	 *            取消按钮名称 必填
	 * @param positiveBtnListener
	 *            监听器,需实现android.content.DialogInterface.OnClickListener接口 必填
	 * @param negativeBtnListener
	 *            监听器,需实现android.content.DialogInterface.OnClickListener接口 必填
	 */
	@SuppressLint("NewApi")
	public static Dialog createConfirmDialog(Context context, String title,
			String message, String positiveBtnName, String negativeBtnName,
			OnClickListener positiveBtnListener,
			OnClickListener negativeBtnListener, int iconId, boolean flag)
	{
		Dialog dialog = null;
		AlertDialog.Builder builder = new AlertDialog.Builder(context,
				AlertDialog.THEME_HOLO_LIGHT);

		if (iconId != NO_ICON)
		{
			// 设置对话框图标
			builder.setIcon(iconId);
		}
		// 设置对话框标题
		builder.setTitle(title);
		// 设置对话框消息
		builder.setMessage(message);
		// 设置确定按钮
		builder.setPositiveButton(positiveBtnName, positiveBtnListener);
		// 设置取消按钮
		builder.setNegativeButton(negativeBtnName, negativeBtnListener);
		// 创建一个消息对话框
		dialog = builder.create();
		// 点击其它地方可以让窗口消失
		dialog.setCancelable(flag);

		return dialog;
	}

	/**
	 * @description 创建单选对话框
	 * 
	 * @param context
	 *            上下文 必填
	 * @param iconId
	 *            图标,如:R.drawable.icon 或 DialogTool.NO_ICON 必填
	 * @param title
	 *            标题 必填
	 * @param itemsString
	 *            选择项 必填
	 * @param positiveBtnName
	 *            确定按钮名称 必填
	 * @param negativeBtnName
	 *            取消按钮名称 必填
	 * @param positiveBtnListener
	 *            监听器,需实现android.content.DialogInterface.OnClickListener接口 必填
	 * @param negativeBtnListener
	 *            监听器,需实现android.content.DialogInterface.OnClickListener接口 必填
	 * @param itemClickListener
	 *            监听器,需实现android.content.DialogInterface.OnClickListener接口 必填
	 * @return
	 */
	public static Dialog createSingleChoiceDialog(Context context,
			String title, String[] itemsString, String positiveBtnName,
			String negativeBtnName, OnClickListener positiveBtnListener,
			OnClickListener negativeBtnListener,
			OnClickListener itemClickListener, int iconId, boolean flag)
	{
		Dialog dialog = null;
		AlertDialog.Builder builder = new AlertDialog.Builder(context);

		if (iconId != NO_ICON)
		{
			// 设置对话框图标
			builder.setIcon(iconId);
		}
		// 设置对话框标题
		builder.setTitle(title);
		// 设置单选选项, 参数0: 默认第一个单选按钮被选中
		builder.setSingleChoiceItems(itemsString, 0, itemClickListener);
		// 设置确定按钮
		builder.setPositiveButton(positiveBtnName, positiveBtnListener);
		// 设置确定按钮
		builder.setNegativeButton(negativeBtnName, negativeBtnListener);
		// 创建一个消息对话框
		dialog = builder.create();

		// 点击其它地方可以让窗口消失
		dialog.setCancelable(flag);

		return dialog;
	}

	/**
	 * @description 创建复选对话框
	 * 
	 * @param context
	 *            上下文 必填
	 * @param iconId
	 *            图标,如:R.drawable.icon 或 DialogTool.NO_ICON 必填
	 * @param title
	 *            标题 必填
	 * @param itemsString
	 *            选择项 必填
	 * @param positiveBtnName
	 *            确定按钮名称 必填
	 * @param negativeBtnName
	 *            取消按钮名称 必填
	 * @param positiveBtnListener
	 *            监听器,需实现android.content.DialogInterface.OnClickListener接口 必填
	 * @param negativeBtnListener
	 *            监听器,需实现android.content.DialogInterface.OnClickListener接口 必填
	 * @param itemClickListener
	 *            监听器,需实现android.content.DialogInterface.
	 *            OnMultiChoiceClickListener;接口 必填
	 * @return
	 */
	public static Dialog createMultiChoiceDialog(Context context, String title,
			String[] itemsString, String positiveBtnName,
			String negativeBtnName, OnClickListener positiveBtnListener,
			OnClickListener negativeBtnListener,
			OnMultiChoiceClickListener itemClickListener, int iconId,
			boolean flag)
	{
		Dialog dialog = null;
		AlertDialog.Builder builder = new AlertDialog.Builder(context);

		if (iconId != NO_ICON)
		{
			// 设置对话框图标
			builder.setIcon(iconId);
		}
		// 设置对话框标题
		builder.setTitle(title);
		// 设置选项
		builder.setMultiChoiceItems(itemsString, null, itemClickListener);
		// 设置确定按钮
		builder.setPositiveButton(positiveBtnName, positiveBtnListener);
		// 设置确定按钮
		builder.setNegativeButton(negativeBtnName, negativeBtnListener);
		// 创建一个消息对话框
		dialog = builder.create();
		// 点击其它地方可以让窗口消失
		dialog.setCancelable(flag);

		return dialog;
	}

	/**
	 * @description 创建列表对话框
	 * 
	 * @param context
	 *            上下文 必填
	 * @param iconId
	 *            图标,如:R.drawable.icon 或 DialogTool.NO_ICON 必填
	 * @param title
	 *            标题 必填
	 * @param itemsString
	 *            列表项 必填
	 * @param negativeBtnName
	 *            取消按钮名称 必填
	 * @param negativeBtnListener
	 *            监听器,需实现android.content.DialogInterface.OnClickListener接口 必填
	 * @return
	 */
	public static Dialog createListDialog(Context context, String title,
			String[] itemsString, String negativeBtnName,
			OnClickListener negativeBtnListener,
			OnClickListener itemClickListener, int iconId, boolean flag)
	{
		Dialog dialog = null;
		AlertDialog.Builder builder = new AlertDialog.Builder(context);

		if (iconId != NO_ICON)
		{
			// 设置对话框图标
			builder.setIcon(iconId);
		}
		// 设置对话框标题
		builder.setTitle(title);
		// 设置列表选项
		builder.setItems(itemsString, itemClickListener);
		// 设置确定按钮
		builder.setNegativeButton(negativeBtnName, negativeBtnListener);
		// 创建一个消息对话框
		dialog = builder.create();
		// 点击其它地方可以让窗口消失
		dialog.setCancelable(flag);

		return dialog;
	}

	/**
	 * @description 创建自定义(含确认、取消)对话框
	 * 
	 * @param context
	 *            上下文 必填
	 * @param iconId
	 *            图标,如:R.drawable.icon 或 DialogTool.NO_ICON 必填
	 * @param title
	 *            标题 必填
	 * @param positiveBtnName
	 *            确定按钮名称 必填
	 * @param negativeBtnName
	 *            取消按钮名称 必填
	 * @param positiveBtnListener
	 *            监听器,需实现android.content.DialogInterface.OnClickListener接口 必填
	 * @param negativeBtnListener
	 *            监听器,需实现android.content.DialogInterface.OnClickListener接口 必填
	 * @param view
	 *            对话框中自定义视图 必填
	 * @return
	 */
	@SuppressLint("NewApi")
	public static Dialog createRandomDialog(Context context, String title,
			String positiveBtnName, String negativeBtnName,
			OnClickListener positiveBtnListener,
			OnClickListener negativeBtnListener, View view, int iconId,
			boolean flag)
	{
		Dialog dialog = null;
		AlertDialog.Builder builder = new AlertDialog.Builder(context,
				AlertDialog.THEME_HOLO_LIGHT);

		if (iconId != NO_ICON)
		{
			// 设置对话框图标
			builder.setIcon(iconId);
		}
		// 设置对话框标题
		builder.setTitle(title);
		builder.setView(view);
		// 设置确定按钮
		builder.setPositiveButton(positiveBtnName, positiveBtnListener);
		// 设置确定按钮
		builder.setNegativeButton(negativeBtnName, negativeBtnListener);
		// 创建一个消息对话框
		dialog = builder.create();
		// 设置点击屏幕其他地方是否消失
		dialog.setCancelable(flag);

		return dialog;
	}

	/**
	 * @description 创建警示(确认、取消)对话框
	 * 
	 * @param context
	 *            上下文 必填
	 * @param iconId
	 *            图标,如:R.drawable.icon 或 DialogTool.NO_ICON 必填
	 * @param title
	 *            标题 必填
	 * @param message
	 *            显示内容 必填
	 * @param positiveBtnName
	 *            确定按钮名称 必填
	 * @param negativeBtnName
	 *            取消按钮名称 必填
	 * @param positiveBtnListener
	 *            监听器,需实现android.content.DialogInterface.OnClickListener接口 必填
	 * @param negativeBtnListener
	 *            监听器,需实现android.content.DialogInterface.OnClickListener接口 必填
	 */
	@SuppressLint("NewApi")
	public static Dialog createEnsureDialog(Context context, View aboutView2,
			String title, String message, String positiveBtnName,
			OnClickListener positiveBtnListener, int iconId, boolean flag)
	{
		Dialog dialog = null;
		AlertDialog.Builder builder = new AlertDialog.Builder(context,
				AlertDialog.THEME_HOLO_LIGHT);
		// LayoutInflater factory = LayoutInflater.from(context);
		// View aboutView = factory.inflate(aboutView2, null);// 获得自定义对话框
		builder.setView(aboutView2);

		if (iconId != NO_ICON)
		{
			// 设置对话框图标
			builder.setIcon(iconId);
		}
		// 设置对话框标题
		builder.setTitle(title);
		// 设置对话框消息
		builder.setMessage(message);
		// 设置确定按钮
		builder.setPositiveButton(positiveBtnName, positiveBtnListener);
		// //设置取消按钮
		// builder.setNegativeButton(negativeBtnName, negativeBtnListener);
		// 创建一个消息对话框
		dialog = builder.create();
		// 点击其它地方可以让窗口消失
		dialog.setCancelable(flag);

		return dialog;
	}
}</span>
文件操作类:

<span style="font-size:18px;">public class FileUtil {
	private static final int BUFF_SIZE = 1048576; // 1M Byte

	/**
	 * @方法描述  复制单个文件 </br> 
	 * @参数  oldFile 源文件 newFile 复制后的新文件
	 * */
	public static boolean copyFile(File oldFile, File newFile) {
		if (oldFile == null && newFile == null) {
			return false;
		}
		try {
			@SuppressWarnings("unused")
			int bytesum = 0;
			int byteread = 0;
			if (oldFile.exists()) {
				// 文件存在时
				InputStream inStream = new FileInputStream(oldFile); // 读入原文件
				FileOutputStream fs = new FileOutputStream(newFile);
				byte[] buffer = new byte[1024];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
					fs.write(buffer, 0, byteread);
				}
				fs.flush();
				fs.close();
				inStream.close();
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 方法描述: 复制单个文件 </br> 参数: oldPath 源文件路径 newPath 复制后的新文件路径
	 * */
	public static boolean copyFile(String oldPath, String newPath) {
		return copyFile(new File(oldPath), new File(newPath));
	}

	/**
	 * 方法描述: 将文件夹下的所有文件复制到新的文件夹下 </br> 参数: oldFile 源文件夹 newFile 复制后的新文件夹 <span>	</span>*/
	@SuppressWarnings("resource")
	public static boolean copyFiles(File oldFile, File newFile) {
		{
			if (!oldFile.exists()) {
				return false;
			}
			byte[] b = new byte[(int) oldFile.length()];
			if (oldFile.isFile()) {
				try {
					FileInputStream is = new FileInputStream(oldFile);
					FileOutputStream ps = new FileOutputStream(newFile);
					is.read(b);
					ps.write(b);
				} catch (Exception e) {
					e.printStackTrace();
					return false;
				}
			} else if (oldFile.isDirectory()) {
				if (!oldFile.exists())
					oldFile.mkdir();
				String[] list = oldFile.list();
				for (int i = 0; i < list.length; i++) {
					copyFiles(oldFile.getAbsolutePath() + "/" + list[i], newFile.getAbsolutePath() + "/" + list[i]);
				}
			}
		}
		return true;
	}

	/**
	 * 方法描述: 将文件夹下的所有文件复制到新的文件夹下 </br> 参数:oldPath 源文件夹路径 newPath 复制后的新文件夹路径
	 * */
	public static boolean copyFiles(String oldPath, String newPath) {
		return copyFiles(new File(oldPath), new File(newPath));
	}

	/**
	 * 方法描述: 将文件夹下的所有文件删除  参数: File 源文件夹
	 * */
	public static boolean delFiles(File file) {
		if (file.isFile()) {
			file.delete();
		}
		if (file.isDirectory()) {
			File[] childFile = file.listFiles();
			if (childFile == null || childFile.length == 0) {
				file.delete();
			}
			for (File f : childFile) {
				delFiles(f);
			}
			// file.delete();
		}
		return true;
	}

	/**
	 * 方法描述: 将文件夹下的所有文件删除 </br> 参数: File 源文件夹 </br> 创 建 人: </br> 创建时间:</br>
	 * */
	public static boolean delFiles(String Path) {
		return delFiles(new File(Path));
	}

	/**
	 * 方法描述: 获取文件夹下某格式的所有文件列表 </br> 参数: File 源文件夹 suffixName 后缀名 例如 ".zip"</br>
	 * 返回值:针对该文件夹的相对路径列表
	 * */
	public static List<String> getSimpleFileList(File file, String suffixName) {
		List<String> list = new ArrayList<String>();
		String path = "";
		if (!file.exists()) {
			return null;
		}
		// 创建fileArray名字的数组
		File[] fileArray = file.listFiles();
		// 如果传进来一个以文件作为对象的allList 返回0
		if (null == fileArray) {
			return null;
		}
		// 偏历目录下的文件
		for (int i = 0; i < fileArray.length; i++) {
			// 如果是个目录
			if (fileArray[i].isDirectory()) {
				// 递归调用
				list.addAll(getSimpleFileList(fileArray[i].getAbsoluteFile(), suffixName));

			} else if (fileArray[i].isFile()) {
				// 如果是以“”结尾的文件
				if (suffixName == null || fileArray[i].getName().endsWith(suffixName)) {
					// 展示文件
					path = fileArray[i].getAbsolutePath();
					Log.e("@@@@@", path);
					list.add(path);
				}
			}
		}
		return list;
	}

	/**
	 * 方法描述: 获取文件夹下某格式的所有文件列表 </br> 参数: path 源文件夹路径 suffixName 后缀名 例如
	 * ".zip"</br> 返回值:针对该文件夹的相对路径列表
	 * */
	public static List<String> getSimpleFileList(String path, String suffixName) {
		return getSimpleFileList(new File(path), suffixName);
	}

	/**
	 * 获得指定文件的byte数组
	 * 
	 * @param filePath
	 *            文件路径
	 * @return byte数组
	 */
	public static byte[] getBytes(String filePath) {
		byte[] buffer = null;
		try {
			File file = new File(URLDecoder.decode(filePath, "UTF-8"));
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
			byte[] b = new byte[1000];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			fis.close();
			bos.close();
			buffer = bos.toByteArray();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer;
	}

	/**
	 * 根据byte数组,生成文件
	 * 
	 * @param bfile
	 *            byte流
	 * @param filePath
	 *            文件路径
	 * @param fileName
	 *            文件名称
	 */
	public static void getFile(byte[] bfile, String filePath, String fileName) {
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		File file = null;
		try {
			File dir = new File(filePath);
			if (!dir.exists() && dir.isDirectory()) {
				// 判断文件目录是否存在
				dir.mkdirs();
			}
			file = new File(filePath + "\\" + fileName);
			fos = new FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			bos.write(bfile);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

	/**
	 * @description 从assets文件夹中拷贝数据到sd卡中
	 * @param context
	 *            上下文环境
	 * @param assetsNamee
	 *            资源文件名
	 * @param strOutFilePath
	 *            拷贝到指定路径
	 * @throws IOException
	 */
	public static void copyDataToSD(Context context, String assetsNamee, String strOutFilePath) throws IOException {
		InputStream myInput;
		OutputStream myOutput = new FileOutputStream(strOutFilePath + "/" + assetsNamee);
		myInput = context.getAssets().open(assetsNamee);
		byte[] buffer = new byte[1024];
		int length = myInput.read(buffer);
		while (length > 0) {
			myOutput.write(buffer, 0, length);
			length = myInput.read(buffer);
		}
		myOutput.flush();
		myInput.close();
		myOutput.close();
	}

	/**
	 * @description 获取文件夹的大小
	 * 
	 * @param f
	 *            文件夹
	 * @return size 文件大小
	 * @throws Exception
	 */
	public static long getFileSize(File f) throws Exception {
		long size = 0;
		File flist[] = f.listFiles();
		for (int i = 0; i < flist.length; i++) {
			if (flist[i].isDirectory()) {
				size = size + getFileSize(flist[i]);
			} else {
				size = size + flist[i].length();
			}
		}
		return size;
	}

	/**
	 * @description 加载本地图片
	 * 
	 * @param url
	 *            本地图片地址
	 * @return Bitmap
	 */
	public static Bitmap getLoacalBitmap(String url) {
		try {
			FileInputStream fis = new FileInputStream(url);
			return BitmapFactory.decodeStream(fis);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * @description 文件夹内是否存在文件。是返回true
	 * 
	 * @param file
	 *            文件夹
	 * @return true/false
	 */
	public static boolean havefile(File file) {
		File[] files = file.listFiles();
		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()) {
					havefile(files[i]);
				} else {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * @description 获取文件内容
	 * @param strFilePath
	 *            文件地址
	 * @return content 文件内容字符串
	 * @throws IOException
	 */
	public static String ReadTxtFile(String strFilePath) throws IOException {
		String path = strFilePath;
		String content = ""; // 文件内容字符串
		// 打开文件
		File file = new File(path);
		// 如果path是传递过来的参数,可以做一个非目录的判断
		if (!file.isDirectory()) {
			InputStream instream = new FileInputStream(file);
			if (instream != null) {
				InputStreamReader inputreader = new InputStreamReader(instream);
				BufferedReader buffreader = new BufferedReader(inputreader);
				String line;
				// 分行读取
				while ((line = buffreader.readLine()) != null) {
					content += line;
				}
				instream.close();
			}
		}
		return content;
	}

	/**
	 * @description 解压缩ZIP文件,将ZIP文件里的内容解压到targetDIR目录下
	 * @param zipName
	 *            待解压缩的ZIP文件名 /mnt/sdcard/ce.zip
	 * @param targetBaseDirName
	 *            目标目录 /mnt/sdcard/cache/
	 */
	public static void upzipFile(String zipFileName, String targetBaseDirName) throws IOException {
		if (!targetBaseDirName.endsWith(File.separator)) {
			targetBaseDirName += File.separator;
		}

		// 根据ZIP文件创建ZipFile对象
		@SuppressWarnings("resource")
		ZipFile myZipFile = new ZipFile(zipFileName);
		ZipEntry entry = null;
		String entryName = null;
		String targetFileName = null;
		byte[] buffer = new byte[4096];
		int bytes_read;
		// 获取ZIP文件里所有的entry
		Enumeration<?> entrys = myZipFile.entries();
		// 遍历所有entry
		while (entrys.hasMoreElements()) {
			entry = (ZipEntry) entrys.nextElement();
			// 获得entry的名字
			entryName = entry.getName();
			targetFileName = targetBaseDirName + entryName;
			if (entry.isDirectory()) {
				// 如果entry是一个目录,则创建目录
				new File(targetFileName).mkdirs();
				continue;
			} else {
				// 如果entry是一个文件,则创建父目录
				new File(targetFileName).getParentFile().mkdirs();
			}
			// 否则创建文件
			File targetFile = new File(targetFileName);
			// System.out.println("创建文件:" + targetFile.getAbsolutePath());
			// 打开文件输出流
			FileOutputStream os = new FileOutputStream(targetFile);
			// 从ZipFile对象中打开entry的输入流
			InputStream is = myZipFile.getInputStream(entry);
			while ((bytes_read = is.read(buffer)) != -1) {
				os.write(buffer, 0, bytes_read);
			}
			// 关闭流
			os.close();
			is.close();
		}
	}

	/**
	 * @description 压缩文件
	 * @param resFile
	 *            需要压缩的文件(夹) F://cc/ or F://abc.txt
	 * @param zipout
	 *            压缩的目的文件
	 * @param rootpath
	 *            压缩的文件路径
	 * @throws FileNotFoundException
	 *             找不到文件时抛出
	 * @throws IOException
	 *             当压缩过程出错时抛出
	 */
	public static void zipFile(File resFile, ZipOutputStream zipout, String rootpath) throws FileNotFoundException, IOException {
		rootpath = rootpath + (rootpath.trim().length() == 0 ? "" : File.separator) + resFile.getName();
		rootpath = new String(rootpath.getBytes("8859_1"), "UTF-8");
		if (resFile.isDirectory()) {
			File[] fileList = resFile.listFiles();
			for (File file : fileList) {
				zipFile(file, zipout, rootpath);
			}
		} else {
			byte buffer[] = new byte[BUFF_SIZE];
			BufferedInputStream in = new BufferedInputStream(new FileInputStream(resFile), BUFF_SIZE);
			zipout.putNextEntry(new ZipEntry(rootpath));
			int realLength;
			while ((realLength = in.read(buffer)) != -1) {
				zipout.write(buffer, 0, realLength);
			}
			in.close();
			zipout.flush();
			zipout.closeEntry();
		}
	}

	/**
	 * @description 
	 *              将存放在sourceFilePath目录下的源文件,打包成fileName名称的ZIP文件,并存放到zipFilePath
	 * 
	 * @param sourceFilePath
	 *            待压缩的文件路径
	 * @param zipFilePath
	 *            压缩后存放路径
	 * @param fileName
	 *            压缩后文件的名称
	 * @return flag 压缩是否成功
	 */
	public static boolean fileToZip(String sourceFilePath, String zipFilePath, String fileName) throws IOException {
		boolean flag = false;
		File sourceFile = new File(sourceFilePath);
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		FileOutputStream fos = null;
		ZipOutputStream zos = null;
		if (sourceFile.exists() == false) {
		} else {
			File zipFile = new File(zipFilePath + "/" + fileName + ".zip");
			File[] sourceFiles = sourceFile.listFiles();
			if (null == sourceFiles || sourceFiles.length < 1) {
			} else {
				fos = new FileOutputStream(zipFile);
				zos = new ZipOutputStream(new BufferedOutputStream(fos));
				byte[] bufs = new byte[1024 * 10];
				for (int i = 0; i < sourceFiles.length; i++) {
					// 创建ZIP实体,并添加进压缩包
					// if(sourceFiles[i].getName().contains(".p12")||sourceFiles[i].getName().contains(".truststore")){
					ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
					zos.putNextEntry(zipEntry);
					// 读取待压缩的文件并写进压缩包里
					fis = new FileInputStream(sourceFiles[i]);
					bis = new BufferedInputStream(fis, 1024 * 10);
					int read = 0;
					while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
						zos.write(bufs, 0, read);
					}
					bis.close();
					fis.close();
					// }
				}
				flag = true;
			}
			zos.close();
			fos.close();
		}
		return flag;
	}
}</span>
MD5操作类:

<span style="font-size:18px;">public class MD5Util 
{
	/**
	 * 将字符串进行MD5加密
	 * 
	 * @param pstr 被加密的字符串
	 * @return MD5 string
	 */
	public static String ToMD5(String pstr)
	{
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		try
		{
			MessageDigest md5Temp = MessageDigest.getInstance("MD5");
			md5Temp.update(pstr.getBytes("UTF8"));
			byte[] md = md5Temp.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;
		}
	}
}
</span>
验证管理:

<span style="font-size:18px;">public class StrUtil {
	  /**
     * 验证Email
     * @param email email地址,格式:zhangsan@sina.com,zhangsan@xxx.com.cn,xxx代表邮件服务商
     * @return 验证成功返回true,验证失败返回false
     */ 
    public static boolean checkEmail(String email) { 
        String regex = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?"; 
        return Pattern.matches(regex, email); 
    } 
     
    /**
     * 验证身份证号码
     * @param idCard 居民身份证号码15位或18位,最后一位可能是数字或字母
     * @return 验证成功返回true,验证失败返回false
     */ 
    public static boolean checkIdCard(String idCard) { 
        String regex = "[1-9]\\d{13,16}[a-zA-Z0-9]{1}"; 
        return Pattern.matches(regex,idCard); 
    } 
     
    /**
     * 验证手机号码(支持国际格式,+86135xxxx...(中国内地),+00852137xxxx...(中国香港))
     * @param mobile 移动、联通、电信运营商的号码段
     *<p>移动的号段:134(0-8)、135、136、137、138、139、147(预计用于TD上网卡)
     *、150、151、152、157(TD专用)、158、159、187(未启用)、188(TD专用)</p>
     *<p>联通的号段:130、131、132、155、156(世界风专用)、185(未启用)、186(3g)</p>
     *<p>电信的号段:133、153、180(未启用)、189</p>
     * @return 验证成功返回true,验证失败返回false
     */ 
    public static boolean checkMobile(String mobile) { 
        String regex = "(\\+\\d+)?1[3458]\\d{9}$"; 
        return Pattern.matches(regex,mobile); 
    } 
     
    /**
     * 验证固定电话号码
     * @param phone 电话号码,格式:国家(地区)电话代码 + 区号(城市代码) + 电话号码,如:+8602085588447
     * <p><b>国家(地区) 代码 :</b>标识电话号码的国家(地区)的标准国家(地区)代码。它包含从 0 到 9 的一位或多位数字,
     *  数字之后是空格分隔的国家(地区)代码。</p>
     * <p><b>区号(城市代码):</b>这可能包含一个或多个从 0 到 9 的数字,地区或城市代码放在圆括号——
     * 对不使用地区或城市代码的国家(地区),则省略该组件。</p>
     * <p><b>电话号码:</b>这包含从 0 到 9 的一个或多个数字 </p>
     * @return 验证成功返回true,验证失败返回false
     */ 
    public static boolean checkPhone(String phone) { 
        String regex = "(\\+\\d+)?(\\d{3,4}\\-?)?\\d{7,8}$"; 
        return Pattern.matches(regex, phone); 
    } 
     
    /**
     * 验证整数(正整数和负整数)
     * @param digit 一位或多位0-9之间的整数
     * @return 验证成功返回true,验证失败返回false
     */ 
    public static boolean checkDigit(String digit) { 
        String regex = "\\-?[1-9]\\d+"; 
        return Pattern.matches(regex,digit); 
    } 
     
    /**
     * 验证整数和浮点数(正负整数和正负浮点数)
     * @param decimals 一位或多位0-9之间的浮点数,如:1.23,233.30
     * @return 验证成功返回true,验证失败返回false
     */ 
    public static boolean checkDecimals(String decimals) { 
        String regex = "\\-?[1-9]\\d+(\\.\\d+)?"; 
        return Pattern.matches(regex,decimals); 
    }  
     
    /**
     * 验证空白字符
     * @param blankSpace 空白字符,包括:空格、\t、\n、\r、\f、\x0B
     * @return 验证成功返回true,验证失败返回false
     */ 
    public static boolean checkBlankSpace(String blankSpace) { 
        String regex = "\\s+"; 
        return Pattern.matches(regex,blankSpace); 
    } 
     
    /**
     * 验证中文
     * @param chinese 中文字符
     * @return 验证成功返回true,验证失败返回false
     */ 
    public static boolean checkChinese(String chinese) { 
        String regex = "^[\u4E00-\u9FA5]+$"; 
        return Pattern.matches(regex,chinese); 
    } 
     
    /**
     * 验证日期(年月日)
     * @param birthday 日期,格式:1992-09-03,或1992.09.03
     * @return 验证成功返回true,验证失败返回false
     */ 
    public static boolean checkBirthday(String birthday) { 
        String regex = "[1-9]{4}([-./])\\d{1,2}\\1\\d{1,2}"; 
        return Pattern.matches(regex,birthday); 
    } 
     
    /**
     * 验证URL地址
     * @param url 格式:http://blog.csdn.net:80/xyang81/article/details/7705960? 或 http://www.csdn.net:80
     * @return 验证成功返回true,验证失败返回false
     */ 
    public static boolean checkURL(String url) { 
        String regex = "(https?://(w{3}\\.)?)?\\w+\\.\\w+(\\.[a-zA-Z]+)*(:\\d{1,5})?(/\\w*)*(\\??(.+=.*)?(&.+=.*)?)?"; 
        return Pattern.matches(regex, url); 
    } 
     
    /**
     * 匹配中国邮政编码
     * @param postcode 邮政编码
     * @return 验证成功返回true,验证失败返回false
     */ 
    public static boolean checkPostcode(String postcode) { 
        String regex = "[1-9]\\d{5}"; 
        return Pattern.matches(regex, postcode); 
    } 
     
    /**
     * 匹配IP地址(简单匹配,格式,如:192.168.1.1,127.0.0.1,没有匹配IP段的大小)
     * @param ipAddress IPv4标准地址
     * @return 验证成功返回true,验证失败返回false
     */ 
    public static boolean checkIpAddress(String ipAddress) { 
        String regex = "[1-9](\\d{1,2})?\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))"; 
        return Pattern.matches(regex, ipAddress); 
    } 
     
} </span>
SD卡相关的辅助:

<span style="font-size:18px;">public class SDCardUtils
{
	private SDCardUtils()
	{
		/* cannot be instantiated */
		throw new UnsupportedOperationException("cannot be instantiated");
	}

	/**
	 * 判断SDCard是否可用
	 * 
	 * @return
	 */
	public static boolean isSDCardEnable()
	{
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);

	}

	/**
	 * 获取SD卡路径
	 * 
	 * @return
	 */
	public static String getSDCardPath()
	{
		return Environment.getExternalStorageDirectory().getAbsolutePath()
				+ File.separator;
	}

	/**
	 * 获取SD卡的剩余容量 单位byte
	 * 
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static long getSDCardAllSize()
	{
		if (isSDCardEnable())
		{
			StatFs stat = new StatFs(getSDCardPath());
			// 获取空闲的数据块的数量
			long availableBlocks = (long) stat.getAvailableBlocks() - 4;
			// 获取单个数据块的大小(byte)
			long freeBlocks = stat.getAvailableBlocks();
			return freeBlocks * availableBlocks;
		}
		return 0;
	}

	/**
	 * 获取指定路径所在空间的剩余可用容量字节数,单位byte
	 * 
	 * @param filePath
	 * @return 容量字节 SDCard可用空间,内部存储可用空间
	 */
	@SuppressWarnings("deprecation")
	public static long getFreeBytes(String filePath)
	{
		// 如果是sd卡的下的路径,则获取sd卡可用容量
		if (filePath.startsWith(getSDCardPath()))
		{
			filePath = getSDCardPath();
		} else
		{// 如果是内部存储的路径,则获取内存存储的可用容量
			filePath = Environment.getDataDirectory().getAbsolutePath();
		}
		StatFs stat = new StatFs(filePath);
		long availableBlocks = (long) stat.getAvailableBlocks() - 4;
		return stat.getBlockSize() * availableBlocks;
	}

	/**
	 * 获取系统存储路径
	 * 
	 * @return
	 */
	public static String getRootDirectoryPath()
	{
		return Environment.getRootDirectory().getAbsolutePath();
	}


}
</span>
处理APP操作的工具:

<span style="font-size:18px;">public class AppUtils {

	private AppUtils() {
		/* cannot be instantiated */
		throw new UnsupportedOperationException("cannot be instantiated");

	}

	/**
	 * @Description 判断某一apk是否被安装到设备上
	 * @param context
	 * @param apkPackageName
	 *            app包名
	 * @return boolean
	 * @throws
	 */
	public static boolean appInstalled(Context context, String apkPackageName) {
		PackageInfo packageInfo;
		try {
			packageInfo = context.getPackageManager().getPackageInfo(apkPackageName, 0);
		} catch (NameNotFoundException e) {
			packageInfo = null;
			e.printStackTrace();
		}
		if (packageInfo == null) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 判断该APK是否正在运行
	 * 
	 * @param apkPackageName
	 *            想要判断的应用包名
	 * @return true 正在运行 false 未运行
	 * 
	 * */
	public static boolean appIsRun(Context context, String apkPackageName) {

		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> list = am.getRunningTasks(100);
		for (RunningTaskInfo info : list) {
			if (info.topActivity.getPackageName().equals(apkPackageName) && info.baseActivity.getPackageName().equals(apkPackageName)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取安装应用的详细信息
	 * 
	 * @param packageName
	 *            安装应用的包名
	 * @return AppInfo
	 */
	public static AppInfo getPackageInfo(Context context, String packageName) {
		AppInfo packages = new AppInfo();
		PackageInfo packageInfo = new PackageInfo();
		try {
			packageInfo = context.getPackageManager().getPackageInfo(packageName, 0);
		} catch (NameNotFoundException e) {
			packageInfo = null;
			e.printStackTrace();
			return null;
		}
		if (packageInfo != null) {
			packages.setAppName(packageInfo.applicationInfo.loadLabel(context.getPackageManager()).toString());
			packages.setPackageName(packageInfo.packageName);
			packages.setVersionName(packageInfo.versionName);
			packages.setVersionCode(packageInfo.versionCode);
			packages.setAppIcon(packageInfo.applicationInfo.loadIcon(context.getPackageManager()));
		} else {
			packages = null;
		}
		return packages;
	}

	/**
	 * 获取机器安装软件信息(包名、版本号、版本code、icon)
	 * 
	 * @return ArrayList<AppInfo>
	 */
	public static ArrayList<AppInfo> getPackagesInfo(Context context) {
		ArrayList<AppInfo> appList = new ArrayList<AppInfo>(); // 用来存储获取的应用信息数据
		List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(0);
		for (int i = 0; i < packages.size(); i++) {
			PackageInfo packageInfo = packages.get(i);
			// 非系统应用才会添加至appList
			if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
				AppInfo tmpInfo = new AppInfo();
				tmpInfo = getPackageInfo(context, packageInfo.packageName);
				appList.add(tmpInfo);
			}
		}
		return appList;
	}

	/**
	 * 获取应用程序名称
	 */
	public static String getAppName(Context context) {
		try {
			PackageManager packageManager = context.getPackageManager();
			PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
			int labelRes = packageInfo.applicationInfo.labelRes;
			return context.getResources().getString(labelRes);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * [获取应用程序版本名称信息]
	 * 
	 * @param context
	 * @return 当前应用的版本名称
	 */
	public static String getVersionName(Context context) {
		try {
			PackageManager packageManager = context.getPackageManager();
			PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionName;

		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * app详细信息,包括应用名称,包名,版本号,图标等
	 * */

	static class AppInfo {

		private String appName = "";// 应用名称
		private String packageName = "";// 应用包名
		private String versionName = "";// 版本名称
		private int versionCode = 0;// 版本ID
		private Drawable appIcon = null;// 应用图标

		public String getAppName() {
			return appName;
		}

		public void setAppName(String appName) {
			this.appName = appName;
		}

		public String getPackageName() {
			return packageName;
		}

		public void setPackageName(String packageName) {
			this.packageName = packageName;
		}

		public String getVersionName() {
			return versionName;
		}

		public void setVersionName(String versionName) {
			this.versionName = versionName;
		}

		public int getVersionCode() {
			return versionCode;
		}

		public void setVersionCode(int versionCode) {
			this.versionCode = versionCode;
		}

		public Drawable getAppIcon() {
			return appIcon;
		}

		public void setAppIcon(Drawable appIcon) {
			this.appIcon = appIcon;
		}

	}
}
</span>

SharedPreferences管理:

<span style="font-size:18px;">public class SPUtils
{
	public SPUtils()
	{
		/* cannot be instantiated */
		throw new UnsupportedOperationException("cannot be instantiated");
	}

	/**
	 * 保存在手机里面的文件名
	 */
	public static final String FILE_NAME = "share_data";

	/**
	 * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
	 * 
	 * @param context
	 * @param key
	 * @param object
	 */
	public static void put(Context context, String key, Object object)
	{

		SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
				Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = sp.edit();

		if (object instanceof String)
		{
			editor.putString(key, (String) object);
		} else if (object instanceof Integer)
		{
			editor.putInt(key, (Integer) object);
		} else if (object instanceof Boolean)
		{
			editor.putBoolean(key, (Boolean) object);
		} else if (object instanceof Float)
		{
			editor.putFloat(key, (Float) object);
		} else if (object instanceof Long)
		{
			editor.putLong(key, (Long) object);
		} else
		{
			editor.putString(key, object.toString());
		}

		SharedPreferencesCompat.apply(editor);
	}

	/**
	 * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
	 * 
	 * @param context
	 * @param key
	 * @param defaultObject
	 * @return
	 */
	public static Object get(Context context, String key, Object defaultObject)
	{
		SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
				Context.MODE_PRIVATE);

		if (defaultObject instanceof String)
		{
			return sp.getString(key, (String) defaultObject);
		} else if (defaultObject instanceof Integer)
		{
			return sp.getInt(key, (Integer) defaultObject);
		} else if (defaultObject instanceof Boolean)
		{
			return sp.getBoolean(key, (Boolean) defaultObject);
		} else if (defaultObject instanceof Float)
		{
			return sp.getFloat(key, (Float) defaultObject);
		} else if (defaultObject instanceof Long)
		{
			return sp.getLong(key, (Long) defaultObject);
		}

		return null;
	}

	/**
	 * 移除某个key值已经对应的值
	 * 
	 * @param context
	 * @param key
	 */
	public static void remove(Context context, String key)
	{
		SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
				Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = sp.edit();
		editor.remove(key);
		SharedPreferencesCompat.apply(editor);
	}

	/**
	 * 清除所有数据
	 * 
	 * @param context
	 */
	public static void clear(Context context)
	{
		SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
				Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = sp.edit();
		editor.clear();
		SharedPreferencesCompat.apply(editor);
	}

	/**
	 * 查询某个key是否已经存在
	 * 
	 * @param context
	 * @param key
	 * @return
	 */
	public static boolean contains(Context context, String key)
	{
		SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
				Context.MODE_PRIVATE);
		return sp.contains(key);
	}

	/**
	 * 返回所有的键值对
	 * 
	 * @param context
	 * @return
	 */
	public static Map<String, ?> getAll(Context context)
	{
		SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
				Context.MODE_PRIVATE);
		return sp.getAll();
	}

	/**
	 * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
	 * 
	 * @author zhy
	 * 
	 */
	private static class SharedPreferencesCompat
	{
		private static final Method sApplyMethod = findApplyMethod();

		/**
		 * 反射查找apply的方法
		 * 
		 * @return
		 */
		@SuppressWarnings({ "unchecked", "rawtypes" })
		private static Method findApplyMethod()
		{
			try
			{
				Class clz = SharedPreferences.Editor.class;
				return clz.getMethod("apply");
			} catch (NoSuchMethodException e)
			{
			}

			return null;
		}

		/**
		 * 如果找到则使用apply执行,否则使用commit
		 * 
		 * @param editor
		 */
		public static void apply(SharedPreferences.Editor editor)
		{
			try
			{
				if (sApplyMethod != null)
				{
					sApplyMethod.invoke(editor);
					return;
				}
			} catch (IllegalArgumentException e)
			{
			} catch (IllegalAccessException e)
			{
			} catch (InvocationTargetException e)
			{
			}
			editor.commit();
		}
	}

}</span>
版本管理:
public class VersionUtils {
    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public static String getVersionName(Context context) {
        PackageManager manager = context.getPackageManager();
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String version = info.versionName;
        return version;
    }

    public static String getVersionCode(Context context) {
        PackageManager manager = context.getPackageManager();
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String version = info.versionCode + "";
        return version;
    }
}

其他的一些:

<span style="font-size:18px;">public class Comm {
	private static long lastClickTime;

	/**
	 * 处理按钮被连续点击的问题。
	 * 
	 * @param ms
	 *            毫秒
	 * @return boolean 是否在这段时间内连续点击
	 * */
	public static boolean isFastDoubleClick(int ms) {
		long time = System.currentTimeMillis();
		long timeD = time - lastClickTime;
		if (0 < timeD && timeD < ms) {
			return true;
		}
		lastClickTime = time;
		return false;
	}

	/**
	 * 深度复制内存对象,处理在复制对象特别是集合类时的浅复制
	 * 
	 * @param srcObj
	 *            复制的目标
	 * @return cloneObj 复制后的对象(完全独立的个体)
	 * */
	public static Object depthClone(Object srcObj) {
		Object cloneObj = null;
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			ObjectOutputStream oo = new ObjectOutputStream(out);
			oo.writeObject(srcObj);

			ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
			ObjectInputStream oi = new ObjectInputStream(in);
			cloneObj = oi.readObject();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return cloneObj;
	}

	/**
	 * 判断是否横屏
	 * 
	 * @return true 横屏,false 竖屏
	 */
	public static boolean isLand(Context context) {
		Configuration cf = context.getResources().getConfiguration();
		int ori = cf.orientation;
		if (ori == Configuration.ORIENTATION_LANDSCAPE) {
			return true;
		} else if (ori == Configuration.ORIENTATION_PORTRAIT) {
			return false;
		}
		return false;
	}

	/**
	 * 打开软键盘
	 * 
	 * @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);
	}

	/**
	 * 关闭软键盘
	 * 
	 * @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);
	}
}
</span>
<span style="font-size:18px;">》》》TextView文字中间有横线:</span>
<span style="font-size:18px;">textview.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG); //中划线

setFlags(Paint. STRIKE_THRU_TEXT_FLAG|Paint.ANTI_ALIAS_FLAG);  // 设置中划线并加清晰 </span>
<span style="font-size:18px;">》》》弹出安装app界面:</span>
<span style="font-size:18px;">new Intent(Intent.ACTION_VIEW);
setDataAndType(Uri.fromFile(FilePath),"application/vnd.android.package-archive");
startActivity();</span>
{ 收集序列中有的类并不是博主所写,原作者也找不到,不过在此感谢原作者;收集并不完善,如有意添加资源  可以在评论区留下代码  非常感谢 }











  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值