Android开发中实用工具类总结

来源:互联网 发布:巩义网络招聘平台 编辑:程序博客网 时间:2024/06/05 20:58

一、CommonUtils工具类.

import android.app.Activity;import android.app.AlertDialog;import android.app.Service;import android.content.ComponentName;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.media.AudioManager;import android.media.MediaPlayer;import android.os.Environment;import android.os.Vibrator;import android.view.inputmethod.InputMethodManager;import java.util.regex.Matcher;import java.util.regex.Pattern;import ren.solid.library.R;/** * Created by LW * Date:2017/9/24 * Time:10:03 */public class CommonUtils {    /**     * 是否存在外部存储     *     * @return     */    public static boolean isExternalStorageExists() {        if (Environment.getExternalStorageState().equals(                Environment.MEDIA_MOUNTED)) {            return true;        }        return false;    }    public static void hideKeyboard(Activity activity) {        try {            ((InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE))                    .hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);        } catch (Exception ex) {            ex.printStackTrace();        }    }    /*    * 打开设置网络界面    */    public static void setNetwork(final Context context) {        // 提示对话框        AlertDialog.Builder builder = new AlertDialog.Builder(context);        builder.setCancelable(false);        try {            builder.setTitle("网络设置提示")                    .setMessage("网络连接不可用,是否进行设置?")                    .setPositiveButton("设置",                            new DialogInterface.OnClickListener() {                                @Override                                public void onClick(DialogInterface dialog,                                                    int which) {                                    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);                                }                            })                    .setNegativeButton("取消",                            new DialogInterface.OnClickListener() {                                @Override                                public void onClick(DialogInterface dialog,                                                    int which) {                                    dialog.dismiss();                                }                            }).show();        } catch (Exception e) {            e.printStackTrace();        }    }    /**     * 调用震动器     *     * @param context      调用该方法的Context     * @param milliseconds 震动的时长,单位是毫秒     */    public static void vibrate(final Context context, long milliseconds) {        Vibrator vib = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);        vib.vibrate(milliseconds);    }    /**     * 调用震动器     *     * @param context  调用该方法的Context     * @param pattern  自定义震动模式 。数组中数字的含义依次是[静止时长,震动时长,静止时长,震动时长。。。]时长的单位是毫秒     * @param isRepeat 是否反复震动,如果是true,反复震动,如果是false,只震动一次     */    public static void vibrate(final Context context, long[] pattern, boolean isRepeat) {        Vibrator vib = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);        vib.vibrate(pattern, isRepeat ? 1 : -1);    }    /**     * 播放音乐     *     * @param context     */    public static void playMusic(Context context) {        MediaPlayer mp = MediaPlayer.create(context, R.raw.beep);        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);        mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {            @Override            public void onPrepared(MediaPlayer mediaPlayer) {                mediaPlayer.start();            }        });        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {            @Override            public void onCompletion(MediaPlayer mediaPlayer) {                mediaPlayer.release();            }        });    }}

二、DateUtils工具类对日期处理。

import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.Locale;/** * Created by _SOLID * Date:2017/9/24 * Time:9:58 */public class DateUtils {    public static SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());    public static SimpleDateFormat formatDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());    /**     * 格式化日期     *     * @param date     * @return 年月日     */    public static String formatDate(Date date) {        return formatDate.format(date);    }    /**     * 格式化日期     *     * @param date     * @return 年月日 时分秒     */    public static String formatDateTime(Date date) {        return formatDateTime.format(date);    }    /**     * 判断是不是今天     *     * @param date     * @return     */    public static boolean isToday(Date date) {        Calendar calendar = Calendar.getInstance();        int year = calendar.get(Calendar.YEAR);        int month = calendar.get(Calendar.MONTH);        int day = calendar.get(Calendar.DAY_OF_MONTH);        calendar.setTime(date);        return year == calendar.get(Calendar.YEAR)                && month == calendar.get(Calendar.MONTH)                && day == calendar.get(Calendar.DAY_OF_MONTH);    }    /**     * 将时间戳解析成日期     *     * @param timeInMillis     * @return 年-月-日     */    public static String parseDate(long timeInMillis) {        Calendar calendar = Calendar.getInstance();        calendar.setTimeInMillis(timeInMillis);        Date date = calendar.getTime();        return formatDate(date);    }    /**     * 将时间戳解析成日期     *     * @param timeInMillis     * @return 年-月-日 时:分:秒     */    public static String parseDateTime(long timeInMillis) {        Calendar calendar = Calendar.getInstance();        calendar.setTimeInMillis(timeInMillis);        Date date = calendar.getTime();        return formatDateTime(date);    }    /**     * 解析日期     *     * @param date 年-月-日     * @return     */    public static Date parseDate(String date) {        Date mDate = null;        try {            mDate = formatDate.parse(date);        } catch (ParseException e) {            e.printStackTrace();        }        return mDate;    }    /**     * 解析日期     *     * @param datetime     * @return     */    public static Date parseDateTime(String datetime) {        Date mDate = null;        try {            mDate = formatDateTime.parse(datetime);        } catch (ParseException e) {            e.printStackTrace();        }        return mDate;    }    /**     * 以友好的方式显示时间     *     * @param sdate     * @return     */    public static String friendlyTime(String sdate) {        Date time = parseDateTime(sdate);        if (time == null) {            return "Unknown";        }        String ftime = "";        Calendar cal = Calendar.getInstance();        // 判断是否是同一天        String curDate = formatDate.format(cal.getTime());        String paramDate = formatDate.format(time);        if (curDate.equals(paramDate)) {            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);            if (hour == 0)                ftime = Math.max(                        (cal.getTimeInMillis() - time.getTime()) / 60000, 1)                        + "分钟前";            else                ftime = hour + "小时前";            return ftime;        }        long lt = time.getTime() / 86400000;        long ct = cal.getTimeInMillis() / 86400000;        int days = (int) (ct - lt);        if (days == 0) {            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);            if (hour == 0)                ftime = Math.max(                        (cal.getTimeInMillis() - time.getTime()) / 60000, 1)                        + "分钟前";            else                ftime = hour + "小时前";        } else if (days == 1) {            ftime = "昨天";        } else if (days == 2) {            ftime = "前天";        } else if (days > 2 && days <= 10) {            ftime = days + "天前";        } else if (days > 10) {            ftime = formatDate.format(time);        }        return ftime;    }}

三、FileUtils工具栏对文件处理。

import android.content.Context;import android.os.Environment;import android.text.TextUtils;import android.util.Log;import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;/** * Created by LW * Date:2017/9/24 * Time:15:01 */public class FileUtils {    private static String TAG = "FileUtils";    private static String FILE_WRITING_ENCODING = "UTF-8";    private static String FILE_READING_ENCODING = "UTF-8";    public static String readFile(String _sFileName, String _sEncoding) throws Exception {        StringBuffer buffContent = null;        String sLine;        FileInputStream fis = null;        BufferedReader buffReader = null;        if (_sEncoding == null || "".equals(_sEncoding)) {            _sEncoding = FILE_READING_ENCODING;        }        try {            fis = new FileInputStream(_sFileName);            buffReader = new BufferedReader(new InputStreamReader(fis,                    _sEncoding));            boolean zFirstLine = "UTF-8".equalsIgnoreCase(_sEncoding);            while ((sLine = buffReader.readLine()) != null) {                if (buffContent == null) {                    buffContent = new StringBuffer();                } else {                    buffContent.append("\n");                }                if (zFirstLine) {                    sLine = removeBomHeaderIfExists(sLine);                    zFirstLine = false;                }                buffContent.append(sLine);            }// end while            return (buffContent == null ? "" : buffContent.toString());        } catch (FileNotFoundException ex) {            throw new Exception("要读取的文件没有找到!", ex);        } catch (IOException ex) {            throw new Exception("读取文件时错误!", ex);        } finally {            // 增加异常时资源的释放            try {                if (buffReader != null)                    buffReader.close();                if (fis != null)                    fis.close();            } catch (Exception ex) {                ex.printStackTrace();            }        }    }    public static File writeFile(String path, String content, String encoding, boolean isOverride) throws Exception {        if (TextUtils.isEmpty(encoding)) {            encoding = FILE_WRITING_ENCODING;        }        InputStream is = new ByteArrayInputStream(content.getBytes(encoding));        return writeFile(is, path, isOverride);    }    public static File writeFile(InputStream is, String path, boolean isOverride) throws Exception {        String sPath = extractFilePath(path);        if (!pathExists(sPath)) {            makeDir(sPath, true);        }        if (!isOverride && fileExists(path)) {            if (path.contains(".")) {                String suffix = path.substring(path.lastIndexOf("."));                String pre = path.substring(0, path.lastIndexOf("."));                path = pre + "_" + System.currentTimeMillis() + suffix;            } else {                path = path + "_" + System.currentTimeMillis();            }        }        FileOutputStream os = null;        File file = null;        try {            file = new File(path);            os = new FileOutputStream(file);            int byteCount = 0;            byte[] bytes = new byte[1024];            while ((byteCount = is.read(bytes)) != -1) {                os.write(bytes, 0, byteCount);            }            os.flush();            return file;        } catch (Exception e) {            e.printStackTrace();            throw new Exception("写文件错误", e);        } finally {            try {                if (os != null)                    os.close();                if (is != null)                    is.close();            } catch (Exception e) {                e.printStackTrace();            }        }    }    /**     * 移除字符串中的BOM前缀     *     * @param _sLine 需要处理的字符串     * @return 移除BOM后的字符串.     */    private static String removeBomHeaderIfExists(String _sLine) {        if (_sLine == null) {            return null;        }        String line = _sLine;        if (line.length() > 0) {            char ch = line.charAt(0);            // 使用while是因为用一些工具看到过某些文件前几个字节都是0xfffe.            // 0xfeff,0xfffe是字节序的不同处理.JVM中,一般是0xfeff            while ((ch == 0xfeff || ch == 0xfffe)) {                line = line.substring(1);                if (line.length() == 0) {                    break;                }                ch = line.charAt(0);            }        }        return line;    }    /**     * 从文件的完整路径名(路径+文件名)中提取 路径(包括:Drive+Directroy )     *     * @param _sFilePathName     * @return     */    public static String extractFilePath(String _sFilePathName) {        int nPos = _sFilePathName.lastIndexOf('/');        if (nPos < 0) {            nPos = _sFilePathName.lastIndexOf('\\');        }        return (nPos >= 0 ? _sFilePathName.substring(0, nPos + 1) : "");    }    /**     * 检查指定文件的路径是否存在     *     * @param _sPathFileName 文件名称(含路径)     * @return 若存在,则返回true;否则,返回false     */    public static boolean pathExists(String _sPathFileName) {        String sPath = extractFilePath(_sPathFileName);        return fileExists(sPath);    }    public static boolean fileExists(String _sPathFileName) {        File file = new File(_sPathFileName);        return file.exists();    }    /**     * 创建目录     *     * @param _sDir             目录名称     * @param _bCreateParentDir 如果父目录不存在,是否创建父目录     * @return     */    public static boolean makeDir(String _sDir, boolean _bCreateParentDir) {        boolean zResult = false;        File file = new File(_sDir);        if (_bCreateParentDir)            zResult = file.mkdirs(); // 如果父目录不存在,则创建所有必需的父目录        else            zResult = file.mkdir(); // 如果父目录不存在,不做处理        if (!zResult)            zResult = file.exists();        return zResult;    }    public static void moveRawToDir(Context context, String rawName, String dir) {        try {            writeFile(context.getAssets().open(rawName), dir, true);        } catch (Exception e) {            e.printStackTrace();            Log.e(TAG, e.getMessage());        }    }    /**     * 得到手机的缓存目录     *     * @param context     * @return     */    public static File getCacheDir(Context context) {        Log.i("getCacheDir", "cache sdcard state: " + Environment.getExternalStorageState());        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {            File cacheDir = context.getExternalCacheDir();            if (cacheDir != null && (cacheDir.exists() || cacheDir.mkdirs())) {                Log.i("getCacheDir", "cache dir: " + cacheDir.getAbsolutePath());                return cacheDir;            }        }        File cacheDir = context.getCacheDir();        Log.i("getCacheDir", "cache dir: " + cacheDir.getAbsolutePath());        return cacheDir;    }    /**     * 得到皮肤目录     *     * @param context     * @return     */    public static File getSkinDir(Context context) {        File skinDir = new File(getCacheDir(context), "skin");        if (skinDir.exists()) {            skinDir.mkdirs();        }        return skinDir;    }    public static String getSkinDirPath(Context context) {        return getSkinDir(context).getAbsolutePath();    }    public static String getSaveImagePath(Context context) {        String path = getCacheDir(context).getAbsolutePath();        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {            path = Environment.getExternalStorageDirectory().getAbsolutePath()                    + File.separator + Environment.DIRECTORY_DCIM;        } else {            path = path + File.separator + "Pictures";        }        File file = new File(path);        if (!file.exists()) {            file.mkdir();        }        return path;    }    public static String generateFileNameByTime() {        return System.currentTimeMillis() + "";    }    public static String getFileName(String path) {        int index = path.lastIndexOf('/');        return path.substring(index + 1);    }}

四、KeyBoardUtils工具类对系统快keyboard进行显示或关闭。

import android.app.Activity;import android.content.Context;import android.view.View;import android.view.inputmethod.InputMethodManager;/** * Created by LW * Date:2017/9/24 * Time:9:30 */public final class KeyboardUtils {    private KeyboardUtils() {    }    public static void showKeyboard(Activity activity, View view) {        if (activity != null) {            if (view != null) {                view.requestFocus();            }            InputMethodManager imm = (InputMethodManager)                    activity.getSystemService(Context.INPUT_METHOD_SERVICE);            if (imm != null) {                imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);            }        }    }    public static void hideKeyboard(Activity activity) {        if (activity != null) {            InputMethodManager imm = (InputMethodManager)                    activity.getSystemService(Context.INPUT_METHOD_SERVICE);            if (imm != null && activity.getCurrentFocus() != null) {                imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);                activity.getCurrentFocus().clearFocus();            }        }    }    public static void hideKeyboard(Activity activity, View view) {        if (activity != null) {            if (view != null) {                InputMethodManager imm = (InputMethodManager)                        activity.getSystemService(Context.INPUT_METHOD_SERVICE);                if (imm != null) {                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);                }            } else {                hideKeyboard(activity);            }        }    }}

五、NetworkUtils工具类,对网络相关进行操作。

import android.content.Context;import android.content.Intent;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.telephony.TelephonyManager;import java.net.InetAddress;import java.net.UnknownHostException;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;/** * <pre> *     author: LW *     blog  : http://blankj.com *     time  : 2017/9/24 *     desc  : 网络相关工具类 * </pre> */public class NetworkUtil {    private NetworkUtil() {        throw new UnsupportedOperationException("u can't instantiate me...");    }    public static final int NETWORK_WIFI = 1;    // wifi network    public static final int NETWORK_4G = 4;    // "4G" networks    public static final int NETWORK_3G = 3;    // "3G" networks    public static final int NETWORK_2G = 2;    // "2G" networks    public static final int NETWORK_UNKNOWN = 5;    // unknown network    public static final int NETWORK_NO = -1;   // no network    private static final int NETWORK_TYPE_GSM = 16;    private static final int NETWORK_TYPE_TD_SCDMA = 17;    private static final int NETWORK_TYPE_IWLAN = 18;    private static final String CMCC_ISP = "46000"; //中国移动    private static final String CMCC2_ISP = "46002";//中国移动    private static final String CU_ISP = "46001";   //中国联通    private static final String CT_ISP = "46003";   //中国电信    /**     * 打开网络设置界面     * <p>3.0以下打开设置界面</p>     *     * @param context 上下文     */    public static void openWirelessSettings(Context context) {        if (android.os.Build.VERSION.SDK_INT > 10) {            context.startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));        } else {            context.startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));        }    }    /**     * 获取活动网络信息     *     * @param context 上下文     * @return NetworkInfo     */    private static NetworkInfo getActiveNetworkInfo(Context context) {        ConnectivityManager cm = (ConnectivityManager) context                .getSystemService(Context.CONNECTIVITY_SERVICE);        return cm.getActiveNetworkInfo();    }    /**     * 判断网络是否可用     * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}</p>     *     * @param context 上下文     * @return {@code true}: 可用<br>{@code false}: 不可用     */    public static boolean isAvailable(Context context) {        NetworkInfo info = getActiveNetworkInfo(context);        return info != null && info.isAvailable();    }    /**     * 判断网络是否连接     * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}</p>     *     * @param context 上下文     * @return {@code true}: 是<br>{@code false}: 否     */    public static boolean isConnected(Context context) {        NetworkInfo info = getActiveNetworkInfo(context);        return info != null && info.isConnected();    }    /**     * 判断网络是否是4G     * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}</p>     *     * @param context 上下文     * @return {@code true}: 是<br>{@code false}: 不是     */    public static boolean is4G(Context context) {        NetworkInfo info = getActiveNetworkInfo(context);        return info != null && info.isAvailable() && info.getSubtype() == TelephonyManager.NETWORK_TYPE_LTE;    }    /**     * 判断wifi是否连接状态     * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}</p>     *     * @param context 上下文     * @return {@code true}: 连接<br>{@code false}: 未连接     */    public static boolean isWifiConnected(Context context) {        ConnectivityManager cm = (ConnectivityManager) context                .getSystemService(Context.CONNECTIVITY_SERVICE);        return cm != null && cm.getActiveNetworkInfo() != null                && cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;    }    /**     * 获取移动网络运营商名称     * <p>中国移动、如中国联通、中国电信</p>     *     * @param context 上下文     * @return 移动网络运营商名称     */    public static String getNetworkOperatorName(Context context) {        TelephonyManager tm = (TelephonyManager) context                .getSystemService(Context.TELEPHONY_SERVICE);        String np = tm != null ? tm.getNetworkOperatorName() : null;        String teleCompany = "unknown";        if (np != null) {            if (np.equals(CMCC_ISP) || np.equals(CMCC2_ISP)) {                teleCompany = "中国移动";            } else if (np.startsWith(CU_ISP)) {                teleCompany = "中国联通";            } else if (np.startsWith(CT_ISP)) {                teleCompany = "中国电信";            }        }        return teleCompany;    }    /**     * 获取移动终端类型     *     * @param context 上下文     * @return 手机制式     * <ul>     * <li>{@link TelephonyManager#PHONE_TYPE_NONE } : 0 手机制式未知</li>     * <li>{@link TelephonyManager#PHONE_TYPE_GSM  } : 1 手机制式为GSM,移动和联通</li>     * <li>{@link TelephonyManager#PHONE_TYPE_CDMA } : 2 手机制式为CDMA,电信</li>     * <li>{@link TelephonyManager#PHONE_TYPE_SIP  } : 3</li>     * </ul>     */    public static int getPhoneType(Context context) {        TelephonyManager tm = (TelephonyManager) context                .getSystemService(Context.TELEPHONY_SERVICE);        return tm != null ? tm.getPhoneType() : -1;    }    /**     * 获取当前的网络类型(WIFI,2G,3G,4G)     * <p>需添加权限 {@code <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>}</p>     *     * @param context 上下文     * @return 网络类型     * <ul>     * <li>{@link #NETWORK_WIFI   } = 1;</li>     * <li>{@link #NETWORK_4G     } = 4;</li>     * <li>{@link #NETWORK_3G     } = 3;</li>     * <li>{@link #NETWORK_2G     } = 2;</li>     * <li>{@link #NETWORK_UNKNOWN} = 5;</li>     * <li>{@link #NETWORK_NO     } = -1;</li>     * </ul>     */    public static int getNetWorkType(Context context) {        int netType = NETWORK_NO;        NetworkInfo info = getActiveNetworkInfo(context);        if (info != null && info.isAvailable()) {            if (info.getType() == ConnectivityManager.TYPE_WIFI) {                netType = NETWORK_WIFI;            } else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {                switch (info.getSubtype()) {                    case NETWORK_TYPE_GSM:                    case TelephonyManager.NETWORK_TYPE_GPRS:                    case TelephonyManager.NETWORK_TYPE_CDMA:                    case TelephonyManager.NETWORK_TYPE_EDGE:                    case TelephonyManager.NETWORK_TYPE_1xRTT:                    case TelephonyManager.NETWORK_TYPE_IDEN:                        netType = NETWORK_2G;                        break;                    case NETWORK_TYPE_TD_SCDMA:                    case TelephonyManager.NETWORK_TYPE_EVDO_A:                    case TelephonyManager.NETWORK_TYPE_UMTS:                    case TelephonyManager.NETWORK_TYPE_EVDO_0:                    case TelephonyManager.NETWORK_TYPE_HSDPA:                    case TelephonyManager.NETWORK_TYPE_HSUPA:                    case TelephonyManager.NETWORK_TYPE_HSPA:                    case TelephonyManager.NETWORK_TYPE_EVDO_B:                    case TelephonyManager.NETWORK_TYPE_EHRPD:                    case TelephonyManager.NETWORK_TYPE_HSPAP:                        netType = NETWORK_3G;                        break;                    case NETWORK_TYPE_IWLAN:                    case TelephonyManager.NETWORK_TYPE_LTE:                        netType = NETWORK_4G;                        break;                    default:                        String subtypeName = info.getSubtypeName();                        if (subtypeName.equalsIgnoreCase("TD-SCDMA")                                || subtypeName.equalsIgnoreCase("WCDMA")                                || subtypeName.equalsIgnoreCase("CDMA2000")) {                            netType = NETWORK_3G;                        } else {                            netType = NETWORK_UNKNOWN;                        }                        break;                }            } else {                netType = NETWORK_UNKNOWN;            }        }        return netType;    }    /**     * 获取当前的网络类型(WIFI,2G,3G,4G)     * <p>依赖上面的方法</p>     *     * @param context 上下文     * @return 网络类型名称     * <ul>     * <li>NETWORK_WIFI   </li>     * <li>NETWORK_4G     </li>     * <li>NETWORK_3G     </li>     * <li>NETWORK_2G     </li>     * <li>NETWORK_UNKNOWN</li>     * <li>NETWORK_NO     </li>     * </ul>     */    public static String getNetWorkTypeName(Context context) {        switch (getNetWorkType(context)) {            case NETWORK_WIFI:                return "NETWORK_WIFI";            case NETWORK_4G:                return "NETWORK_4G";            case NETWORK_3G:                return "NETWORK_3G";            case NETWORK_2G:                return "NETWORK_2G";            case NETWORK_NO:                return "NETWORK_NO";            default:                return "NETWORK_UNKNOWN";        }    }    /**     * 根据域名获取ip地址     *     * @param domain 域名     * @return ip地址     */    public static String getIpAddress(final String domain) {        try {            ExecutorService exec = Executors.newCachedThreadPool();            Future<String> fs = exec.submit(new Callable<String>() {                @Override                public String call() throws Exception {                    InetAddress inetAddress;                    try {                        inetAddress = InetAddress.getByName(domain);                        return inetAddress.getHostAddress();                    } catch (UnknownHostException e) {                        e.printStackTrace();                        return null;                    }                }            });            return fs.get();        } catch (InterruptedException | ExecutionException e) {            e.printStackTrace();            return null;        }    }}

六、NumberUtils工具类,对电话号码运营商进行判断。

/** * Created by LW * Date:2017/9/24 * Time:10:12 */public class NumberUtils {    /**     * 中国移动拥有号码段为:139,138,137,136,135,134,159,158,157(3G),151,150,188(3G),187(3G     * );13个号段 中国联通拥有号码段为:130,131,132,156(3G),186(3G),185(3G);6个号段     * 中国电信拥有号码段为:133,153,189(3G),180(3G);4个号码段     */    private static String mRegMobileStr = "^1(([3][456789])|([5][01789])|([8][78]))[0-9]{8}$";    private static String mRegMobile3GStr = "^((157)|(18[78]))[0-9]{8}$";    private static String mRegUnicomStr = "^1(([3][012])|([5][6])|([8][56]))[0-9]{8}$";    private static String mRegUnicom3GStr = "^((156)|(18[56]))[0-9]{8}$";    private static String mRegTelecomStr = "^1(([3][3])|([5][3])|([8][09]))[0-9]{8}$";    private static String mRegTelocom3GStr = "^(18[09])[0-9]{8}$";    private static String mRegPhoneString = "^(?:13\\d|15\\d)\\d{5}(\\d{3}|\\*{3})$";    private String mobile = "";    private int facilitatorType = 0;    private boolean isLawful = false;    private boolean is3G = false;    public NumberUtils(String mobile)    {        this.setMobile(mobile);    }    public void setMobile(String mobile)    {        if (mobile == null)        {            return;        }        /** */        /** 第一步判断中国移动 */        if (mobile.matches(NumberUtils.mRegMobileStr))        {            this.mobile = mobile;            this.setFacilitatorType(0);            this.setLawful(true);            if (mobile.matches(NumberUtils.mRegMobile3GStr))            {                this.setIs3G(true);            }        }        /** */        /** 第二步判断中国联通 */        else if (mobile.matches(NumberUtils.mRegUnicomStr))        {            this.mobile = mobile;            this.setFacilitatorType(1);            this.setLawful(true);            if (mobile.matches(NumberUtils.mRegUnicom3GStr))            {                this.setIs3G(true);            }        }        /** */        /** 第三步判断中国电信 */        else if (mobile.matches(NumberUtils.mRegTelecomStr))        {            this.mobile = mobile;            this.setFacilitatorType(2);            this.setLawful(true);            if (mobile.matches(NumberUtils.mRegTelocom3GStr))            {                this.setIs3G(true);            }        }        /** */        /** 第四步判断座机 */        if (mobile.matches(NumberUtils.mRegPhoneString))        {            this.mobile = mobile;            this.setFacilitatorType(0);            this.setLawful(true);            if (mobile.matches(NumberUtils.mRegMobile3GStr))            {                this.setIs3G(true);            }        }    }    public String getMobile()    {        return mobile;    }    public int getFacilitatorType()    {        return facilitatorType;    }    public boolean isLawful()    {        return isLawful;    }    public boolean isIs3G()    {        return is3G;    }    private void setFacilitatorType(int facilitatorType)    {        this.facilitatorType = facilitatorType;    }    private void setLawful(boolean isLawful)    {        this.isLawful = isLawful;    }    private void setIs3G(boolean is3G)    {        this.is3G = is3G;    }}

七、StringUtils工具类,对String进行操作。

import android.util.Log;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.util.regex.Matcher;import java.util.regex.Pattern;/** * Created by LW * Date:2017/9/24 * Time:16:11 */public class StringUtils {    /**     * 将字符串进行md5转换     *     * @param str     * @return     */    public static String md5(String str) {        String cacheKey;        try {            final MessageDigest mDigest = MessageDigest.getInstance("MD5");            mDigest.update(str.getBytes());            cacheKey = bytesToHexString(mDigest.digest());        } catch (NoSuchAlgorithmException e) {            cacheKey = String.valueOf(str.hashCode());        }        return cacheKey;    }    private static String bytesToHexString(byte[] bytes) {        StringBuilder sb = new StringBuilder();        for (int i = 0; i < bytes.length; i++) {            String hex = Integer.toHexString(0xFF & bytes[i]);            if (hex.length() == 1) {                sb.append('0');            }            sb.append(hex);        }        return sb.toString();    }    public static boolean isNullOrEmpty(String s) {        return s == null || s.length() == 0;    }    /**     * 清除文本里面的HTML标签     *     * @param htmlStr     * @return     */    public static String clearHTMLTag(String htmlStr) {        String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式        String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式        String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式        Log.v("htmlStr", htmlStr);        try {            Pattern p_script = Pattern.compile(regEx_script,                    Pattern.CASE_INSENSITIVE);            Matcher m_script = p_script.matcher(htmlStr);            htmlStr = m_script.replaceAll(""); // 过滤script标签            Pattern p_style = Pattern.compile(regEx_style,                    Pattern.CASE_INSENSITIVE);            Matcher m_style = p_style.matcher(htmlStr);            htmlStr = m_style.replaceAll(""); // 过滤style标签            Pattern p_html = Pattern.compile(regEx_html,                    Pattern.CASE_INSENSITIVE);            Matcher m_html = p_html.matcher(htmlStr);            htmlStr = m_html.replaceAll(""); // 过滤html标签        } catch (Exception e) {            htmlStr = "clear error";        }        return htmlStr; // 返回文本字符串    }    /**     * 字符串转整数     *     * @param str     * @param defValue     * @return     */    public static int toInt(String str, int defValue) {        try {            return Integer.parseInt(str);        } catch (Exception e) {        }        return defValue;    }    /**     * 对象转整数     *     * @param str     * @return 转换异常返回 0     */    public static int toInt(String str) {        if (str == null)            return 0;        return toInt(str.toString(), 0);    }    /**     * 对象转整数     *     * @param str     * @return 转换异常返回 0     */    public static long toLong(String str) {        try {            return Long.parseLong(str);        } catch (Exception e) {        }        return 0;    }    /**     * 字符串转布尔值     *     * @param b     * @return 转换异常返回 false     */    public static boolean toBool(String b) {        try {            return Boolean.parseBoolean(b);        } catch (Exception e) {        }        return false;    }}

八、SystemUtils工具类,对系统一些操作。

import android.content.Context;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import android.provider.Settings;import android.telephony.TelephonyManager;import android.text.TextUtils;/** * 与系统有关的工具类 * Created by LW * Date:2017/9/24 * Time:19:37 */public class SystemUtils {    /**     * 获取设备的制造商     *     * @return 设备制造商     */    public static String getDeviceManufacture() {        return android.os.Build.MANUFACTURER;    }    /**     * 获取设备名称     *     * @return 设备名称     */    public static String getDeviceName() {        return android.os.Build.MODEL;    }    /**     * 获取系统版本号     *     * @return 系统版本号     */    public static String getSystemVersion() {        return android.os.Build.VERSION.RELEASE;    }    /**     * 获取设备号     *     * @param context     * @return     */    public static String getDeviceIMEI(Context context) {        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);        if (telephonyManager == null || TextUtils.isEmpty(telephonyManager.getDeviceId())) {            return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);        } else {            return telephonyManager.getDeviceId();        }    }    /**     * 获取应用的版本号     *     * @param context     * @return     */    public static String getAppVersion(Context context) {        PackageManager packageManager = context.getPackageManager();        PackageInfo packageInfo;        try {            packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);            return packageInfo.versionName;        } catch (PackageManager.NameNotFoundException e) {            e.printStackTrace();        }        return null;    }}

九、ToastUtils工具类。

import android.content.Context;import android.widget.Toast;/** * Created by LW * Date:2017/9/24 * Time:16:44 */public class ToastUtils {    private static Context mContext;    private static ToastUtils mInstance;    private Toast mToast;    public static ToastUtils getInstance() {        return mInstance;    }    public static void init(Context ctx) {        mInstance = new ToastUtils(ctx);    }    private ToastUtils(Context ctx) {        mContext = ctx;    }    public void showToast(String text) {        if (mToast == null) {            mToast = Toast.makeText(mContext, text, Toast.LENGTH_SHORT);        } else {            mToast.setText(text);            mToast.setDuration(Toast.LENGTH_LONG);        }        mToast.show();    }    public void cancelToast() {        if (mToast != null) {            mToast.cancel();        }    }}

十、ViewUtils工具类。

import android.content.Context;import android.content.res.TypedArray;import android.util.DisplayMetrics;import android.util.TypedValue;import ren.solid.library.fragment.base.BaseFragment;/** * Created by LW * Date:2017/9/24 * Time:19:37 */public class ViewUtils {    /**     * 根据Class创建Fragment     *     * @param clazz the Fragment of create     * @return     */    public static BaseFragment createFragment(Class<?> clazz) {        BaseFragment resultFragment = null;        String className = clazz.getName();        try {            try {                resultFragment = (BaseFragment) Class.forName(className).newInstance();            } catch (InstantiationException e) {                e.printStackTrace();            } catch (IllegalAccessException e) {                e.printStackTrace();            }        } catch (ClassNotFoundException e) {            e.printStackTrace();        }        return resultFragment;    }    public static DisplayMetrics getDisplayMetrics(Context context) {        return context.getResources().getDisplayMetrics();    }    /**     * 获取屏幕的宽度     *     * @param context context     * @return     */    public static int getScreenWidth(Context context) {        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();        return displayMetrics.widthPixels;    }    /**     * 获取屏幕的高度     *     * @param context context     * @return     */    public static int getScreenHeight(Context context) {        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();        return displayMetrics.heightPixels;    }    //转换dp为px    public static int dp2px(Context context, int dip) {        float scale = context.getResources().getDisplayMetrics().density;        return (int) (dip * scale + 0.5f * (dip >= 0 ? 1 : -1));    }    //转换px为dp    public static int px2dp(Context context, int px) {        float scale = context.getResources().getDisplayMetrics().density;        return (int) (px / scale + 0.5f * (px >= 0 ? 1 : -1));    }    //转换sp为px    public static int sp2px(Context context, float spValue) {        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;        return (int) (spValue * fontScale + 0.5f);    }    //转换px为sp    public static int px2sp(Context context, float pxValue) {        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;        return (int) (pxValue / fontScale + 0.5f);    }    public static int getThemeColorPrimary(Context ctx) {        TypedValue typedValue = new TypedValue();        ctx.getTheme().resolveAttribute(android.R.attr.theme, typedValue, true);        int[] attribute = new int[]{android.R.attr.colorPrimary};        TypedArray array = ctx.obtainStyledAttributes(typedValue.resourceId, attribute);        int color = array.getColor(0, -1);        array.recycle();        return color;    }    public static int getThemeColorPrimaryDark(Context ctx) {        TypedValue typedValue = new TypedValue();        ctx.getTheme().resolveAttribute(android.R.attr.theme, typedValue, true);        int[] attribute = new int[]{android.R.attr.colorPrimaryDark};        TypedArray array = ctx.obtainStyledAttributes(typedValue.resourceId, attribute);        int color = array.getColor(0, -1);        array.recycle();        return color;    }    public static int getThemeColorAccent(Context ctx) {        TypedValue typedValue = new TypedValue();        ctx.getTheme().resolveAttribute(android.R.attr.theme, typedValue, true);        int[] attribute = new int[]{android.R.attr.colorAccent};        TypedArray array = ctx.obtainStyledAttributes(typedValue.resourceId, attribute);        int color = array.getColor(0, -1);        array.recycle();        return color;    }}

十一、PrefUtils工具类。

import android.content.Context;import android.content.SharedPreferences;import android.preference.PreferenceManager;/** * Created by LW * Date:2017/9/4 * Time:9:32 * <p> * apply与commit异同: * 1. apply没有返回值而commit返回boolean表明修改是否提交成功 * 2. apply是将修改数据原子提交到内存, 而后异步真正提交到硬件磁盘, 而commit是同步的提交到硬件磁盘,因此,在多个并发的提交commit的时候,他们会等待正在处理的commit保存到磁盘后在操作,从而降低了效率。而apply只是原子的提交到内容,后面有调用apply的函数的将会直接覆盖前面的内存数据,这样从一定程度上提高了很多效率。 * 3. apply方法不会提示任何失败的提示。 * 由于在一个进程中,sharedPreference是单实例,一般不会出现并发冲突,如果对提交的结果不关心的话,建议使用apply,当然需要确保提交成功且有后续操作的话,还是需要用commit的。 */public final class PrefUtils {    private PrefUtils() {    }    public static int getInt(Context context, final String key, int defaultValue) {        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);        return prefs.getInt(key, defaultValue);    }    public static void putInt(Context context, String key, int value) {        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);        prefs.edit().putInt(key, value).apply();    }    public static long getLong(Context context, final String key, long defaultValue) {        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);        return prefs.getLong(key, defaultValue);    }    public static void putLong(Context context, String key, long value) {        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);        prefs.edit().putLong(key, value).apply();    }    public static String getString(Context context, final String key, final String defaultValue) {        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);        return prefs.getString(key, defaultValue);    }    public static void putString(Context context, String key, String value) {        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);        prefs.edit().putString(key, value).apply();    }    public static boolean getBoolean(Context context, String key, final boolean defaultValue) {        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);        return prefs.getBoolean(key, defaultValue);    }    public static void putBoolean(Context context, String key, boolean value) {        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);        prefs.edit().putBoolean(key, value).apply();    }    public static void remove(Context context, String key) {        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);        prefs.edit().remove(key).apply();    }}
原创粉丝点击