Android 最常用的快速开发工具类

Android开发的工具类能很好的封装一些常用的操作,以后使用起来也非常方便,我把我经常使用的工具类分享给大家。

FileCache:

package com.pztuan.common.util;

import java.io.File;
import android.content.Context;

public class FileCache {
	private File cacheDir;

	public FileCache(Context context) {
		// 判断外存SD卡挂载状态,如果挂载正常,创建SD卡缓存文件夹
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			cacheDir = new File(
					android.os.Environment.getExternalStorageDirectory(),
					"PztCacheDir");
		} else {
			// SD卡挂载不正常,获取本地缓存文件夹(应用包所在目录)
			cacheDir = context.getCacheDir();
		}
		if (!cacheDir.exists()) {
			cacheDir.mkdirs();
		}
	}

	public File getFile(String url) {
		String fileName = String.valueOf(url.hashCode());
		File file = new File(cacheDir, fileName);
		return file;
	}

	public void clear() {
		File[] files = cacheDir.listFiles();
		for (File f : files)
			f.delete();
	}

	public String getCacheSize() {
		long size = 0;
		if (cacheDir.exists()) {
			File[] files = cacheDir.listFiles();
			for (File f : files) {
				size += f.length();
			}
		}
		String cacheSize = String.valueOf(size / 1024 / 1024) + "M";
		return cacheSize;
	}

}

NetWorkUtil(网络类):

package com.pztuan.common.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.WifiManager;

import java.security.MessageDigest;

/**
 *
 * @author suncat
 * @category 网络工具
 */
public class NetWorkUtil {
	private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
			"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
	public static final int STATE_DISCONNECT = 0;
	public static final int STATE_WIFI = 1;
	public static final int STATE_MOBILE = 2;

	public static String concatUrlParams() {

		return null;
	}

	public static String encodeUrl() {

		return null;
	}

	public static boolean isNetWorkConnected(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] nis = cm.getAllNetworkInfo();
		if (nis != null) {
			for (NetworkInfo ni : nis) {
				if (ni != null) {
					if (ni.isConnected()) {
						return true;
					}
				}
			}
		}

		return false;
	}

	public static boolean isWifiConnected(Context context) {
		WifiManager wifiMgr = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);
		boolean isWifiEnable = wifiMgr.isWifiEnabled();

		return isWifiEnable;
	}

	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = cm.getActiveNetworkInfo();
		if (networkInfo != null) {
			return networkInfo.isAvailable();
		}

		return false;
	}

	private static String byteArrayToHexString(byte[] b) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			resultSb.append(byteToHexString(b[i]));
		}
		return resultSb.toString();
	}

	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0)
			n = 256 + n;
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	public static String md5Encode(String origin) {
		String resultString = null;

		try {
			resultString = new String(origin);
			MessageDigest md = MessageDigest.getInstance("MD5");
			resultString = new String(md.digest(resultString.getBytes()));
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return resultString;
	}

	public static String md5EncodeToHexString(String origin) {
		String resultString = null;

		try {
			resultString = new String(origin);
			MessageDigest md = MessageDigest.getInstance("MD5");
			resultString = byteArrayToHexString(md.digest(resultString
					.getBytes()));
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return resultString;
	}

	public static int getNetworkState(Context context) {
		ConnectivityManager connManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		// Wifi
		State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
				.getState();
		if (state == State.CONNECTED || state == State.CONNECTING) {
			return STATE_WIFI;
		}

		// 3G
		state = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
				.getState();
		if (state == State.CONNECTED || state == State.CONNECTING) {
			return STATE_MOBILE;
		}
		return STATE_DISCONNECT;
	}
}

Tools(常用小功能:号码正则匹配、日期计算、获取imei号、计算listview高度):

package com.pztuan.common.util;

import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

@SuppressLint("DefaultLocale")
public class Tools {

	private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
			"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

	public static String byteArrayToHexString(byte[] b) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			resultSb.append(byteToHexString(b[i]));
		}
		return resultSb.toString();
	}

	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0)
			n = 256 + n;
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	/**
	 * md5 加密
	 *
	 * @param origin
	 * @return
	 */
	public static String md5Encode(String origin) {
		String resultString = null;
		try {
			resultString = new String(origin);
			MessageDigest md = MessageDigest.getInstance("MD5");
			resultString = byteArrayToHexString(md.digest(resultString
					.getBytes()));
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return resultString;
	}

	/**
	 * 手机号码格式匹配
	 *
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0,1,3,5-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		System.out.println(m.matches() + "-telnum-");
		return m.matches();
	}

	/**
	 * 是否含有指定字符
	 *
	 * @param expression
	 * @param text
	 * @return
	 */
	private static boolean matchingText(String expression, String text) {
		Pattern p = Pattern.compile(expression);
		Matcher m = p.matcher(text);
		boolean b = m.matches();
		return b;
	}

	/**
	 * 邮政编码
	 *
	 * @param zipcode
	 * @return
	 */
	public static boolean isZipcode(String zipcode) {
		Pattern p = Pattern.compile("[0-9]\\d{5}");
		Matcher m = p.matcher(zipcode);
		System.out.println(m.matches() + "-zipcode-");
		return m.matches();
	}

	/**
	 * 邮件格式
	 *
	 * @param email
	 * @return
	 */
	public static boolean isValidEmail(String email) {
		Pattern p = Pattern
				.compile("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$");
		Matcher m = p.matcher(email);
		System.out.println(m.matches() + "-email-");
		return m.matches();
	}

	/**
	 * 固话号码格式
	 *
	 * @param telfix
	 * @return
	 */
	public static boolean isTelfix(String telfix) {
		Pattern p = Pattern.compile("d{3}-d{8}|d{4}-d{7}");
		Matcher m = p.matcher(telfix);
		System.out.println(m.matches() + "-telfix-");
		return m.matches();
	}

	/**
	 * 用户名匹配
	 *
	 * @param name
	 * @return
	 */
	public static boolean isCorrectUserName(String name) {
		Pattern p = Pattern.compile("([A-Za-z0-9]){2,10}");
		Matcher m = p.matcher(name);
		System.out.println(m.matches() + "-name-");
		return m.matches();
	}

	/**
	 * 密码匹配,以字母开头,长度 在6-18之间,只能包含字符、数字和下划线。
	 *
	 * @param pwd
	 * @return
	 *
	 */
	public static boolean isCorrectUserPwd(String pwd) {
		Pattern p = Pattern.compile("\\w{6,18}");
		Matcher m = p.matcher(pwd);
		System.out.println(m.matches() + "-pwd-");
		return m.matches();
	}

	/**
	 * 检查是否存在SDCard
	 *
	 * @return
	 */
	public static boolean hasSdcard() {
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 计算剩余日期
	 *
	 * @param remainTime
	 * @return
	 */
	public static String calculationRemainTime(String endTime, long countDown) {

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date now = new Date(System.currentTimeMillis());// 获取当前时间
			Date endData = df.parse(endTime);
			long l = endData.getTime() - countDown - now.getTime();
			long day = l / (24 * 60 * 60 * 1000);
			long hour = (l / (60 * 60 * 1000) - day * 24);
			long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
			long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
			return "剩余" + day + "天" + hour + "小时" + min + "分" + s + "秒";
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static void showLongToast(Context act, String pMsg) {
		Toast toast = Toast.makeText(act, pMsg, Toast.LENGTH_LONG);
		toast.show();
	}

	public static void showShortToast(Context act, String pMsg) {
		Toast toast = Toast.makeText(act, pMsg, Toast.LENGTH_SHORT);
		toast.show();
	}

	/**
	 * 获取手机Imei号
	 *
	 * @param context
	 * @return
	 */
	public static String getImeiCode(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		return tm.getDeviceId();
	}

	/**
	 * @author sunglasses
	 * @param listView
	 * @category 计算listview的高度
	 */
	public static void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			// pre-condition
			return;
		}

		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
	}
}

SharedPreferencesUtil:

package com.pztuan.db;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;

import java.util.ArrayList;
import java.util.Set;

public class SharedPreferencesUtil {
	private static final String TAG = "PZTuan.SharePreferencesUtil";
	private static final String SHAREDPREFERENCE_NAME = "sharedpreferences_pztuan";

	private static SharedPreferencesUtil mInstance;

	private static SharedPreferences mSharedPreferences;

	private static SharedPreferences.Editor mEditor;

	public synchronized static SharedPreferencesUtil getInstance(Context context) {
		if (mInstance == null) {
			mInstance = new SharedPreferencesUtil(context);
		}

		return mInstance;
	}

	private SharedPreferencesUtil(Context context) {
		mSharedPreferences = context.getSharedPreferences(
				SHAREDPREFERENCE_NAME, Context.MODE_PRIVATE);
		mEditor = mSharedPreferences.edit();
	}

	public synchronized boolean putString(String key, String value) {
		mEditor.putString(key, value);
		return mEditor.commit();
	}

	public synchronized boolean putStringArrayList(String key,
			ArrayList<String> value) {

		for (int j = 0; j < value.size() - 1; j++) {
			if (value.get(value.size() - 1).equals(value.get(j))) {
				value.remove(j);
			}
		}
		mEditor.putInt("citySize", value.size());

		if (value.size() == 4) {
			mEditor.putString(key + 0, value.get(3));
			mEditor.putString(key + 1, value.get(0));
			mEditor.putString(key + 2, value.get(1));
		} else if (value.size() == 3) {
			mEditor.putString(key + 0, value.get(2));
			mEditor.putString(key + 1, value.get(0));
			mEditor.putString(key + 2, value.get(1));
		} else {
			for (int i = 0; i < value.size(); i++) {
				mEditor.putString(key + i, value.get(value.size() - 1 - i));
			}

		}
		return mEditor.commit();
	}

	public synchronized boolean putInt(String key, int value) {
		mEditor.putInt(key, value);
		return mEditor.commit();
	}

	public synchronized boolean putLong(String key, long value) {
		mEditor.putLong(key, value);
		return mEditor.commit();
	}

	public synchronized boolean putFloat(String key, float value) {
		mEditor.putFloat(key, value);
		return mEditor.commit();
	}

	public synchronized boolean putBoolean(String key, boolean value) {
		mEditor.putBoolean(key, value);
		return mEditor.commit();
	}

	public synchronized boolean putStringSet(String key, Set<String> value) {
		mEditor.putStringSet(key, value);
		return mEditor.commit();
	}

	public String getString(String key, String value) {
		return mSharedPreferences.getString(key, value);
	}

	public ArrayList<String> getStringArrayList(String key, int size) {
		ArrayList<String> al = new ArrayList<String>();
		int loop;
		if (size > 4)
			loop = 4;
		else
			loop = size;
		for (int i = 0; i < loop; i++) {
			String name = mSharedPreferences.getString(key + i, null);
			al.add(name);
		}
		return al;
	}

	public int getInt(String key, int value) {
		return mSharedPreferences.getInt(key, value);
	}

	public long getLong(String key, long value) {
		return mSharedPreferences.getLong(key, value);
	}

	public float getFloat(String key, float value) {
		return mSharedPreferences.getFloat(key, value);
	}

	public boolean getBoolean(String key, boolean value) {
		return mSharedPreferences.getBoolean(key, value);
	}

	public Set<String> getStringSet(String key, Set<String> value) {
		return mSharedPreferences.getStringSet(key, value);
	}

	public boolean remove(String key) {
		mEditor.remove(key);
		return mEditor.commit();
	}

	private static final String PREFERENCES_AUTO_LOGIN = "yyUserAutoLogin";
	private static final String PREFERENCES_USER_NAME = "yyUserName";
	private static final String PREFERENCES_USER_PASSWORD = "yyUserPassword";

	public boolean isAutoLogin() {
		return mSharedPreferences.getBoolean(PREFERENCES_AUTO_LOGIN, false);
	}

	public String getUserName() {
		return mSharedPreferences.getString(PREFERENCES_USER_NAME, "");
	}

	public String getUserPwd() {
		return mSharedPreferences.getString(PREFERENCES_USER_PASSWORD, "");
	}

	public void saveLoginInfo(Boolean autoLogin, String userName,
			String userPassword) {
		assert (mEditor != null);
		mEditor.putBoolean(PREFERENCES_AUTO_LOGIN, autoLogin);
		mEditor.putString(PREFERENCES_USER_NAME, userName);
		mEditor.putString(PREFERENCES_USER_PASSWORD, userPassword);
		mEditor.commit();
	}

	public void saveLoginPassword(String userPassword) {
		mEditor.putString(PREFERENCES_USER_PASSWORD, userPassword);
		mEditor.commit();
	}

	public void saveLoginUserid(String userid) {
		mEditor.putString("userid", userid);
		mEditor.commit();
	}

	public void clearUserInfo() {
		assert (mEditor != null);
		mEditor.putBoolean(PREFERENCES_AUTO_LOGIN, false);
		mEditor.putString(PREFERENCES_USER_NAME, "");
		mEditor.putString(PREFERENCES_USER_PASSWORD, "");
		mEditor.putString("userid", "");
		mEditor.commit();
	}

}

如有问题请留言,转载注明出处。

时间: 2024-09-29 13:26:58

Android 最常用的快速开发工具类的相关文章

Android快速开发工具类

点我下载代码 更多交流可加技术讨论群:71262831 扫一扫,一起坐看风云变幻.扫描下方二维码关注it达人(也可微信搜索:it达人). 为您推送最新开发资源.分享it牛人职业发展经验:

Android下常用的正则表达式判断工具类代码(手机,电话,Email,日期等待)

package com.yaowen.mytest; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Check { // 判断电话 public static boolean isTelephone(String phonenumber) { String phone = "0\\d{2,3}-\\d{7,8}"; Patt

开发者不可不知的五款DIY快速开发工具,你造吗

对于非专业的移动开发者,弱化编程能力的快发开发工具实用性够强,无需编程只要借助工具提供的各种功能模块,就能开发出属于自己的应用,而支持DIY更能使应用开发锦上添花,借助快速开发工具开发出属于自己的“能嘚瑟”应用,而不是让人捂脸叹息“那画面太美我不敢看” 1.AppMachine AppMachine是一款跨平台的快速开发工具,目前支持iOS和Android两大主流平台,没编程经验的用户可以通过修改AppMachine所提供的20种应用设计模板进行App设计.除此之外,另外用户也可以自己DIY,添

快速开发工具知多少

移动互联网时代,应用间的相互竞争趋白热化,但相关工具的增多也在降低APP开发的技术门槛,快发开发工具更是其中的重要部分,戴维列举几种快速开发工具,供开发者参考和学习,大家一起来看看吧. 1.AppMachine AppMachine 是一个跨iOS和Android平台的快速开发工具,它的方便之处在于提供二十多种应用设计模板,使用者可以直接通过模板进行应用开发.当然,用户也可以自己DIY,添加新闻.LBS.社交媒体.拍照.摄像等多个集成内容.AppMachine 不依赖HTML5,也提供AppMa

开发者必须知道的九款快速开发工具

移动互联网时代,应用间的相互竞争趋白热化,但相关工具的增多也在降低APP开发的技术门槛,快发开发工具更是其中的重要部分,列举几种快速开发工具,供大家参考和学习,一起来看看吧. 1.AppMachine AppMachine 是一个跨iOS和Android平台的快速开发工具,它的方便之处在于提供二十多种应用设计模板,使用者可以直接通过模板进行应用开发.当然,用户也可以自己DIY,添加新闻.LBS.社交媒体.拍照.摄像等多个集成内容.AppMachine 不依赖HTML5,也提供AppMachine

常用cookie处理方法工具类

功能:cookie的添加.删除.获取值 1 import java.io.UnsupportedEncodingException; 2 import java.net.URLDecoder; 3 4 import javax.servlet.http.Cookie; 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpServletResponse; 7 8 /** 9 * 常用cook

安卓快速开发工具集

安卓快速开发工具集 快速开发,能简便开发过程,节省时间. 下载地址:http://www.devstore.cn/code/info/805.html 包含文件:

百度地图V2.0实践项目开发工具类bmap.util.js V1.4

/** * 百度地图使用工具类-v2.0(大眾版) * * @author boonya * @date 2013-7-7 * @address Chengdu,Sichuan,China * @email [email protected] * @company KWT.Shenzhen.Inc.com * @notice 有些功能需要加入外部JS库才能使用,另外还需要申请地图JS key . * 申请地址:http://developer.baidu.com/map/apply-key.ht

Android PermissionUtils:运行时权限工具类及申请权限的正确姿势

Android PermissionUtils:运行时权限工具类及申请权限的正确姿势 ifadai 关注 2017.06.16 16:22* 字数 318 阅读 3637评论 1喜欢 6 PermissionUtil 经常写Android运行时权限申请代码,每次都是复制过来之后,改一下权限字符串就用,把代码搞得乱糟糟的,于是便有了封装工具类的想法,话不多说,先看怎么用: 工具类及Demo:github 简洁版申请权限 申请一个权限: PermissionUtils.checkAndRequest