Tools commonly used in Android 01

Source: Internet
Author: User

1. Image and video thumbnail tool class
Import Android.graphics.bitmap;import android.graphics.bitmapfactory;import android.media.thumbnailutils;/** * Thumbnail generation Tool class * @author * */public class Thumbnailgenerateutils {private Thumbnailgenerateutils () {};/** * to get the thumbnail based on the specified image path and size Figure * This method has two points of benefit: * 1.     Using a smaller memory space, the first fetch of the bitmap is actually null, just to read the width and height, * The second read of the bitmap is based on the proportional compressed image, the third read bitmap is the desired thumbnail. * 2.     Thumbnails are not stretched for the original image, and the 2.2 version of the new tool thumbnailutils is used, so that the images generated with this tool are not stretched. * @param the path of the ImagePath image * @param width specifies the output image widths * @param height Specifies the height of the output image * @return generated thumbnails */public            Static Bitmap Getimagethumbnail (String imagePath, int width, int height) {Bitmap Bitmap = null;            Bitmapfactory.options Options = new Bitmapfactory.options ();            Options.injustdecodebounds = true;            To get the width and height of this picture, note that the bitmap here is null bitmap = Bitmapfactory.decodefile (ImagePath, Options); Options.injustdecodebounds = false;       Set to False//calculate scaling ratio     int h = options.outheight;            int w = options.outwidth;            int bewidth = W/width;            int beheight = H/height;            int be = 1;if (Bewidth < beheight) {is = Bewidth;} else {be = beheight;}            if (be <= 0) {is = 1;            } options.insamplesize = be; Re-read into the picture, read the scaled bitmap, note this time to set Options.injustdecodebounds to False bitmap = Bitmapfactory.decodefile (ImagePath, O            ptions);                            Use Thumbnailutils to create thumbnails, where you specify which bitmap object to scale bitmap = Thumbnailutils.extractthumbnail (bitmap, width, height,            Thumbnailutils.options_recycle_input);    return bitmap;     /** * Get thumbnail image of video * First create a thumbnail of a video by Thumbnailutils, and then use thumbnailutils to generate a thumbnail of the specified size.     * If the desired thumbnail width and height are less than micro_kind, then the type will use Micro_kind as the KIND value, which saves memory. * @param the path of the Videopath video * @param width Specifies the width of the output video thumbnail * @param height Specifies the height of the output video thumbnail * @param kind reference mediastore. Images.thumbConstants Mini_kind and Micro_kind in the nails class. * Where mini_kind:512 x 384,micro_kind:96 x * * @return A video thumbnail of the specified size */public static Bitmap Getvideot            Humbnail (String videopath, int width, int height,int kind) {Bitmap Bitmap = null;            Get thumbnail image of video bitmap = Thumbnailutils.createvideothumbnail (Videopath, kind);            System.out.println ("W" +bitmap.getwidth ());            System.out.println ("H" +bitmap.getheight ()); Bitmap = Thumbnailutils.extractthumbnail (bitmap, width, height, thumbnailutils.options_recycle_            INPUT);    return bitmap; }}

2. Density calculation Tool class
/** * Density Calculation tool *  * @author ZBZHANGC *  */public class Densityutils {public static int dip2px (context context, float D PValue) {Final float scale = context.getresources (). Getdisplaymetrics (). Density;return (Int.) (Dpvalue * scale + 0.5f);} public static int Px2dip (context context, float Pxvalue) {final float scale = context.getresources (). Getdisplaymetrics (). Density;return (int) (Pxvalue/scale + 0.5f);}}
3. Folder creation, file name substitution tool class
Import Java.io.file;import java.text.simpledateformat;import java.util.date;import android.os.environment;/** * File name Action Tool class * @author Zhang * */public class Filenameoperationutils {private static SimpleDateFormat DateFormat = new Simple DateFormat ("yyyy. Mm.dd ");p rivate filenameoperationutils () {};/** * Generate folder * @return Folder path */public static string Generatefoldername (string ProjectName) {String FolderPath = environment.getexternalstoragedirectory () + "/province" + "/" +projectname+ "/" + Dateformat.format (New Date (System.currenttimemillis ())); File Folder = new file (FolderPath), if (!folder.exists ())//Create folder Folder.mkdirs (); return folderpath;} /** * Get picture file name * @return */public static String Getpictruefilename () {return system.currenttimemillis ()/1000+ ". jpg";} /** * Get the video file name * @return */public static String Getvideofilename () {return system.currenttimemillis ()/1000+ ". mp4";} /** * Get audio file name * @return */public static String Getaudiofilename () {return system.currenttimemillis ()/1000+ ". 3gp";} /** * Get the full path name of the picture file * @retuRN */public static string Getpictureabsolutefilename (String projectName) {return Generatefoldername (projectName) + "/" + Getpictruefilename ();} /*** * Gets the full path name of the audio file * @param projectName * @return */public static string Getaudioabsolutefilename (String projectName) {RET Urn Generatefoldername (projectName) + "/" +getaudiofilename ();} /** * Replace folder name * @param fileName * @param newfoldername * @return */public static Boolean renamefolder (String Filename,stri ng newfoldername) {File File = new file (fileName), if (!file.isdirectory ()) {String FolderPath = File.getpath (). SUBSTRING ( 0,file.getpath (). lastIndexOf ("\ \"));//Current folder name string oldfoldername = Folderpath.substring (Folderpath.lastindexof (" \ \ ") +1);//To replace the folder name return new file (FolderPath). Renameto (New file (Folderpath.replace (Oldfoldername, newfoldername)) ;} Else{system.out.println (File.getpath ()); String oldfoldername = File.getpath (). substring (File.getpath (). lastIndexOf ("\ \") +1); System.out.println (oldfoldername); return File.renameto (New file (File.getpath (). Replace (Oldfoldername, NewFolderName)));}}} 
4, prevent users of continuous click
Package Com.iss.starwish.util;import android.content.context;import android.widget.toast;/** * Prevent button continuous click * @author Zhang * */public class Utils {private static long lastclicktime;/*** prevent user in 800ms continuous click **/public static Boolean Isfastdoubl Eclick () {Long time = System.currenttimemillis (); Long TimeD = time-lastclicktime;if (0 < TimeD && TimeD < () {return true;} Lastclicktime = Time;return false;} /** * Show Toast * @param context * @param content */public static void Show (context context,string content) {Toast.maketext (c Ontext, Content, Toast.length_short). Show (); /** * Show Toast * @param context * @param content */public static void Show (context Context,int Strid) {Toast.maketext (Contex T, Strid, Toast.length_short). Show ();}}
5. Convert Chinese characters into pinyinThis is used with the Pinyin4j-2.5.0.jar (which is also the more reliable way of conversion I find on the Internet)
Package Net.tianyouwang.utils;import Net.sourceforge.pinyin4j.pinyinhelper;import Net.sourceforge.pinyin4j.format.hanyupinyincasetype;import Net.sourceforge.pinyin4j.format.hanyupinyinoutputformat;import Net.sourceforge.pinyin4j.format.hanyupinyintonetype;import Net.sourceforge.pinyin4j.format.HanyuPinyinVCharType ; Import Net.sourceforge.pinyin4j.format.exception.badhanyupinyinoutputformatcombination;public Class Chinesetopinyinutil {private Chinesetopinyinutil () {}/*** * man converted to pinyin * @param src * @return */public static String getpingy In (String src) {char[] T1 = NULL;T1 = Src.tochararray (); string[] t2 = new String[t1.length]; hanyupinyinoutputformat t3 = new Hanyupinyinoutputformat (); T3.setcasetype (hanyupinyincasetype.lowercase); T3.settonetype (Hanyupinyintonetype.without_tone); T3.setvchartype (HANYUPINYINVCHARTYPE.WITH_V); String t4 = ""; int t0 = t1.length;try {for (int i = 0; i < t0; i++) {//Determines whether the Kanji character if (java.lang.Character.toString (T1[i]). Matches ("[\\u4e00-\\u9fa5]+")) {t2 = Pinyinhelper. Tohanyupinyinstringarray (T1[i], T3); T4 + = t2[0];} Elset4 + = java.lang.Character.toString (T1[i]);} System.out.println (T4); return t4;} catch (Badhanyupinyinoutputformatcombination E1) {e1.printstacktrace ();} return t4;} Returns the initial public static string Getpinyinheadchar (String str) {string convert = "" In Chinese, and for (int j = 0; J < Str.length (); J + +) {char word = Str.charat (j); string[] Pinyinarray = Pinyinhelper.tohanyupinyinstringarray (word); if (Pinyinarray! = null) {convert + = pinyinarray[0]. CharAt (0);} else {convert + = Word;}} return convert;}}

6. Determine the current network connection type and whether the network is available
Package Net.tianyouwang.utils;import Android.content.context;import Android.net.connectivitymanager;import      Android.net.networkinfo;import Android.telephony.telephonymanager;public class NetUtils {/*** * To determine if the current network is connected * * @param con * @return */public static Boolean isnetworkavailable (context context) {Connectivityma        Nager cm = (connectivitymanager) context. Getsystemservice (Context.connectivity_service);        if (cm = = null) return false;        Networkinfo NetInfo = Cm.getactivenetworkinfo ();        if (NetInfo = = null) {return false;        } if (netinfo.isconnected ()) {return true;    } return false; /**** * Gets the current network type * @param context * @return */public static String Getnetworktype (Context Co ntext) {Connectivitymanager cm = (connectivitymanager) context. Getsystemservice (Context.connectivit        Y_service);     if (cm = = null)       Return "";        Networkinfo NetInfo = Cm.getactivenetworkinfo ();            if (NetInfo! = null) {int type = Netinfo.gettype ();                if (type = = 0) {//Phone int subtype = Netinfo.getsubtype ();                if (subtype = = TELEPHONYMANAGER.NETWORK_TYPE_CDMA) {//Telecom 2G return "2g";                        } else if (subtype = = Telephonymanager.network_type_evdo_0 | | subtype = = Telephonymanager.network_type_evdo_a ||                Subtype = = Telephonymanager.network_type_evdo_b) {//Telecom 3G return "3g";                } else if (subtype = = Telephonymanager.network_type_gprs) {//Unicom 2g return "2g";                } else if (subtype = = Telephonymanager.network_type_edge) {//move 2G return "2g";                        } else if (subtype = = TELEPHONYMANAGER.NETWORK_TYPE_HSDPA | |                Subtype = = Telephonymanager.network_type_umts) {//Unicom 3g return "3g";            } } else if (type = = 1) {//wifi return "WiFi";    }} return "3g"; }}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.