Android中常用的工具類01

來源:互聯網
上載者:User

標籤:android   style   blog   class   code   java   

1、圖片和影片縮圖工具類
import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.media.ThumbnailUtils;/** * 縮圖產生工具類 * @author * */public class ThumbnailGenerateUtils {private ThumbnailGenerateUtils(){};/**     * 根據指定的映像路徑和大小來擷取縮圖     * 此方法有兩點好處:     *     1. 使用較小的記憶體空間,第一次擷取的bitmap實際上為null,只是為了讀取寬度和高度,     *        第二次讀取的bitmap是根據比例壓縮過的映像,第三次讀取的bitmap是所要的縮圖。     *     2. 縮圖對於原映像來講沒有展開,這裡使用了2.2版本的新工具ThumbnailUtils,使     *        用這個工具產生的映像不會被展開。     * @param imagePath 映像的路徑     * @param width 指定輸出映像的寬度     * @param height 指定輸出映像的高度     * @return 產生的縮圖     */    public static Bitmap getImageThumbnail(String imagePath, int width, int height) {            Bitmap bitmap = null;            BitmapFactory.Options options = new BitmapFactory.Options();            options.inJustDecodeBounds = true;            // 擷取這個圖片的寬和高,注意此處的bitmap為null            bitmap = BitmapFactory.decodeFile(imagePath, options);            options.inJustDecodeBounds = false; // 設為 false            // 計算縮放比            int h = options.outHeight;            int w = options.outWidth;            int beWidth = w / width;            int beHeight = h / height;            int be = 1;if (beWidth < beHeight) {be = beWidth;} else {be = beHeight;}            if (be <= 0) {                    be = 1;            }            options.inSampleSize = be;            // 重新讀入圖片,讀取縮放後的bitmap,注意這次要把options.inJustDecodeBounds 設為 false            bitmap = BitmapFactory.decodeFile(imagePath, options);            // 利用ThumbnailUtils來建立縮圖,這裡要指定要縮放哪個Bitmap對象            bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,                            ThumbnailUtils.OPTIONS_RECYCLE_INPUT);            return bitmap;    }    /**     * 擷取視頻的縮圖     * 先通過ThumbnailUtils來建立一個視頻的縮圖,然後再利用ThumbnailUtils來產生指定大小的縮圖。     * 如果想要的縮圖的寬和高都小於MICRO_KIND,則類型要使用MICRO_KIND作為kind的值,這樣會節省記憶體。     * @param videoPath 視頻的路徑     * @param width 指定輸出影片縮圖的寬度     * @param height 指定輸出影片縮圖的高度度     * @param kind 參照MediaStore.Images.Thumbnails類中的常量MINI_KIND和MICRO_KIND。     *            其中,MINI_KIND: 512 x 384,MICRO_KIND: 96 x 96     * @return 指定大小的影片縮圖     */    public static Bitmap getVideoThumbnail(String videoPath, int width, int height,int kind) {            Bitmap bitmap = null;            // 擷取視頻的縮圖            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、密度計算工具類
/** * 密度計算工具 *  * @author zbzhangc *  */public class DensityUtils {public static int dip2px(Context context, float dpValue) {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、檔案夾建立,檔案名稱替換工具類
import java.io.File;import java.text.SimpleDateFormat;import java.util.Date;import android.os.Environment;/** * 檔案名稱操作工具類 * @author zhang * */public class FileNameOperationUtils {private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");private FileNameOperationUtils(){};/** * 組建檔案夾 * @return檔案夾路徑 */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())//建立檔案夾folder.mkdirs();return folderPath;}/** * 擷取圖片檔案名稱 * @return */public static String getPictrueFileName(){return System.currentTimeMillis()/1000+".jpg";}/** * 擷取視頻檔案名稱 * @return */public static String getVideoFileName(){return System.currentTimeMillis()/1000+".mp4";}/** * 擷取音頻檔案名稱 * @return */public static String getAudioFileName(){return System.currentTimeMillis()/1000+".3gp";}/** * 擷取圖片檔案的全路徑名稱 * @return */public static String getPictureAbsoluteFileName(String projectName){return generateFolderName(projectName)+"/"+getPictrueFileName();}/*** * 擷取音頻檔案的全路徑名稱 * @param projectName * @return */public static String getAudioAbsoluteFileName(String projectName){return generateFolderName(projectName)+"/"+getAudioFileName();}/** * 替換檔案夾名稱 * @param fileName * @param newFolderName * @return */public static boolean renameFolder(String fileName,String newFolderName){File file = new File(fileName);if(!file.isDirectory()){String folderPath = file.getPath().substring(0,file.getPath().lastIndexOf("\\"));//當前檔案夾名稱String oldFolderName = folderPath.substring(folderPath.lastIndexOf("\\")+1);//要替換檔案夾名稱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、防止使用者的連續點擊
package com.iss.starwish.util;import android.content.Context;import android.widget.Toast;/** * 防止按鈕連續點擊 * @author zhang * */public class Utils {private static long lastClickTime;/*** 防止使用者在800ms裡面的連續點擊**/public static boolean isFastDoubleClick() {long time = System.currentTimeMillis();long timeD = time - lastClickTime;if (0 < timeD && timeD < 800) {return true;}lastClickTime = time;return false;}/** * 顯示Toast * @param context * @param content */public static void show(Context context,String content){Toast.makeText(context, content, Toast.LENGTH_SHORT).show();}/** * 顯示Toast * @param context * @param content */public static void show(Context context,int strId){Toast.makeText(context, strId, Toast.LENGTH_SHORT).show();}}
5、漢字轉換成拼音 這個和pinyin4j-2.5.0.jar一塊使用(也是我在網上找的比較靠譜的轉換方式)
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() {}/*** * 漢子轉換成拼音 * @param src * @return */public static String getPingYin(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++){// 判斷是否為漢字字元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;}// 返回中文的首字母public static String getPinYinHeadChar(String str) {String convert = "";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、判斷當前網路連接類型和網路是否可用
package net.tianyouwang.utils;import android.content.Context;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.telephony.TelephonyManager;public class NetUtils {    /***     * 判斷當前網路是否串連     *      * @param con     * @return     */    public static boolean isNetworkAvailable(Context context) {        ConnectivityManager 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;    }        /****     * 擷取當前的網路類型     * @param context     * @return     */    public static String getNetWorkType(Context context){        ConnectivityManager cm = (ConnectivityManager) context                .getSystemService(Context.CONNECTIVITY_SERVICE);        if (cm == null)            return "";        NetworkInfo netinfo = cm.getActiveNetworkInfo();        if(netinfo != null){            int type = netinfo.getType();            if(type == 0){//手機                int subtype = netinfo.getSubtype();                if(subtype == TelephonyManager.NETWORK_TYPE_CDMA){//電信2G                    return "2g";                } else if(subtype == TelephonyManager.NETWORK_TYPE_EVDO_0 || subtype == TelephonyManager.NETWORK_TYPE_EVDO_A                        || subtype == TelephonyManager.NETWORK_TYPE_EVDO_B){//電信3G                    return "3g";                } else if(subtype == TelephonyManager.NETWORK_TYPE_GPRS){//聯通2g                    return "2g";                } else if(subtype == TelephonyManager.NETWORK_TYPE_EDGE){//移動2G                    return "2g";                } else if(subtype == TelephonyManager.NETWORK_TYPE_HSDPA ||                        subtype == TelephonyManager.NETWORK_TYPE_UMTS){//聯通3g                    return "3g";                }             } else if(type == 1){//wifi                return "wifi";            }        }        return "3g";    }}




相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.