Android developed tool class can be very good to encapsulate some common operation, later use is also very convenient, I used the tools I often use to share to everyone.
Filecache:
package com.pztuan.common.util;import java.io.file;import android.content.Context; public class Filecache {private File cachedir;public Filecache (Context context) {//Judgment external memory SD card mount status, if mount is normal, create SD card cache folder if ( Android.os.Environment.getExternalStorageState (). Equals (Android.os.Environment.MEDIA_MOUNTED)) {Cachedir = new File (Android.os.Environment.getExternalStorageDirectory (), "Pztcachedir");} else {//SD card is not mounted properly, gets the local cache folder (the directory where the app package resides) 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:file s) {size + = F.length ();}} String cacheSize = string.valueof (size/1024/1024) + "M"; return cacheSize;}}
Networkutil (Network Class):
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 Network tool */public class Networkutil {private final static stri Ng[] hexdigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "B", "C", "D", "E", "F"};p ublic 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.isconnect Ed ()) {return true;}}}} return false;} public static BooleanIswificonnected (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 = n;int + D1 = N/16;int D2 = n 16;return H EXDIGITS[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);//Wifistate state = Connmanager.getnetworkinfo ( Connectivitymanager.type_wifi). GetState (); if (state = = State.connected | | state = = state.connecting) {return State_wifi ;} 3Gstate = Connmanager.getnetworkinfo (connectivitymanager.type_mobile). GetState (); if (state = = State.connected | | state = = state.connecting) {return state_mobile;} return state_disconnect;}}
Tools (Common small functions: number regular match, date calculation, get IMEI number, calculate listview height):
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"};p ublic static String bytearraytohexstring (byte[] b) {StringBuffer RESULTSB = new Stri Ngbuffer (); 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 = n;int + D1 = N/16;int D2 = n 16;retUrn Hexdigits[d1] + hexdigits[d2];} /** * MD5 Encryption * * @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;} /** * Mobile number format matches * * @param mobiles * @return */public static Boolean Ismobileno (String mobiles) {Pattern p = Pattern.compi Le ("^ ((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 ();} /** * contains the specified character * * @param expression * @param text * @return */private static Boolean matchingtext (String expression, Str ing text) {Pattern p = pattern.compile (expression); Matcher m = p.matcher (text); Boolean B = m.matches (); return b;} /** * ZIP Code * * @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 ();} /** * Mail Format * * @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 ();} /** * Fixed number format * * @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 ();} /** * Username 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 ();} /** * Password match, beginning with letter, length between 6-18, can only contain characters, numbers and underscores. * * @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 ();} /** * Check for Presence sdcard * * @return */public static Boolean Hassdcard () {String state = Environment.getexternalstoragestate (); if (State.equals (environment.media_mounted)) {return true;} else {return false;}} /** * Calculates the remaining date * * @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 ()); Gets the current time date Enddata = Df.parse (endTime), long L = enddata.gettime ()-countdown-now.gettime (); Long day = L/(24 * 60 * Long hour = (L/(* * +)-day *); Long min = ((l/(+))-Day * * 60-hour *); long s = (l/1000-day * * 60-hour * * * 60-min *), return "remaining" + Day + "days" + Hour + "hours" + min + "min" + "s +" seconds ";} catch (ParseException e) {E.prinTstacktrace ();} Return "";} public static void Showlongtoast (Context Act, String pMsg) {Toast toast = toast.maketext (Act, PMSG, Toast.length_long); toa St.show ();} public static void Showshorttoast (Context Act, String pMsg) {Toast toast = toast.maketext (Act, PMSG, toast.length_short); t Oast.show ();} /** * Get phone IMEI number * * @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 Calculate the height of the listview */public static void Setlistviewheightbasedonchildren (ListView ListView) {ListAdapter listadapter = Listview.getadapter (); if (listadapter = = null) {//Pre-conditionreturn;} int totalheight = 0;for (int i = 0; i < Listadapter.getcount (); i++) {View ListItem = Listadapter.getview (i, NULL, list View); listitem.measure (0, 0); Totalheight + = Listitem.getmeasuredheight ();} Viewgroup.layoutparams params = listview.getlayoutpaRams ();p arams.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";p rivate static final S Tring Sharedpreference_name = "Sharedpreferences_pztuan";p rivate 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.siz E ()-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.pu Tstring (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;elseloop = size;for (int i = 0; I < loop; i++) {String name = Msharedpre Ferences.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";p rivate static final string preferences_user_name = "Yyusername";p rivate static final String Preferences_user_password = "Yyuserpassword";p ublic 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 ();}}
If you have any questions, please leave a message, reproduced the source.
Android's most popular quick development tool class