android各种常用的方法集合

来源:互联网 发布:java继承的概念 编辑:程序博客网 时间:2024/05/16 12:51

1、常用的方法Utils

public class Utils {    // 记录屏幕的高度、宽度、密度等信息。    public static int screenH;    public static int screenW;    public static float screenDensity; // 屏幕密度(0.75 / 1.0 / 1.5)    public static int screenDensityDpi; // 屏幕密度DPI(120 / 160 / 240)    public static int statusBarHeight; // 状态栏高度    // 获取屏幕的高度和宽度    public static int getScreenW(Activity mActivity) {        if (screenW == 0) {            DisplayMetrics metric = new DisplayMetrics();            mActivity.getWindowManager().getDefaultDisplay().getMetrics(metric);            screenW = metric.widthPixels; // 屏幕宽度(像素)            screenH = metric.heightPixels; // 屏幕高度(像素)            screenDensity = metric.density; // 屏幕密度(0.75 / 1.0 / 1.5)            screenDensityDpi = metric.densityDpi; // 屏幕密度DPI(120 / 160 /        }        return screenW;    }    public static int getScreenH(Activity mActivity) {        if (screenH == 0) {            DisplayMetrics metric = new DisplayMetrics();            mActivity.getWindowManager().getDefaultDisplay().getMetrics(metric);            screenW = metric.widthPixels; // 屏幕宽度(像素)            screenH = metric.heightPixels; // 屏幕高度(像素)            screenDensity = metric.density; // 屏幕密度(0.75 / 1.0 / 1.5)            screenDensityDpi = metric.densityDpi; // 屏幕密度DPI(120 / 160 /        }        return screenH;    }    /**     * 升级检测     *      * @param locVersionName     * @param lastVersion     * @return 是否升级     */    public static boolean checkUpdate(String locVersionName, String lastVersion) {        boolean hasUpdate = false;        String[] locVersionS = locVersionName.split("\\.");        String[] lastVersionS = lastVersion.split("\\.");        if (!locVersionName.equals(lastVersion)) {            if (locVersionS != null && lastVersion != null) {                int localLenth = locVersionS.length;                int lastVerLenth = lastVersionS.length;                // int netLenth = lastVersion.length();                for (int i = 0; i < lastVerLenth; i++) {                    if (localLenth < lastVerLenth && i == localLenth) {                        hasUpdate = true;                        return hasUpdate;                    }                    if (Integer.valueOf(lastVersionS[i]) > Integer                            .valueOf(locVersionS[i])) {                        hasUpdate = true;                        return hasUpdate;                    } else if (Integer.valueOf(lastVersionS[i]) < Integer                            .valueOf(locVersionS[i])) {                        hasUpdate = false;                        return hasUpdate;                    }                }            }        } else {            hasUpdate = false;        }        return hasUpdate;    }    /**     * bitmap转byte数组     *      * @param bmp     * @param needRecycle     * @return     */    public static byte[] bmpToByteArray(final Bitmap bmp,            final boolean needRecycle) {        ByteArrayOutputStream output = new ByteArrayOutputStream();        bmp.compress(CompressFormat.PNG, 100, output);        if (needRecycle) {            bmp.recycle();        }        byte[] result = output.toByteArray();        try {            output.close();        } catch (Exception e) {            e.printStackTrace();        }        return result;    }    /**     * 实现文本复制功能 add by lif     *      * @param content     */    public static void copy(String content, Context context) {        // 得到剪贴板管理器        ClipboardManager cmb = (ClipboardManager) context                .getSystemService(Context.CLIPBOARD_SERVICE);        cmb.setText(content.trim());    }    /**     * 实现粘贴功能 add by lif     *      * @param context     * @return     */    public static String paste(Context context) {        // 得到剪贴板管理器        ClipboardManager cmb = (ClipboardManager) context                .getSystemService(Context.CLIPBOARD_SERVICE);        return cmb.getText().toString().trim();    }    /**     * 隐藏软键盘     */    public static void hideSoftInputMethod(Activity act) {        View view = act.getWindow().peekDecorView();        if (view != null) {            // 隐藏虚拟键盘            InputMethodManager inputmanger = (InputMethodManager) act                    .getSystemService(act.INPUT_METHOD_SERVICE);            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);        }    }    /**     * 切换软件盘 显示隐藏     */    public static void switchSoftInputMethod(Activity act) {        // 方法一(如果输入法在窗口上已经显示,则隐藏,反之则显示)        InputMethodManager imm = (InputMethodManager) act                .getSystemService(Context.INPUT_METHOD_SERVICE);        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);    }    /**     * 验证是否手机号码     *      * @param mobiles     * @return     */    public static boolean isMobileNO(String mobiles) {        Pattern p = Pattern                .compile("^((13[0-9])|(15[^4,//D])|(18[0,5-9]))//d{8}$");        Matcher m = p.matcher(mobiles);        System.out.println(m.matches() + "---");        return m.matches();    }    /**     * 中文识别     *      */    public static boolean hasChinese(String source) {        String reg_charset = "([\\u4E00-\\u9FA5]*+)";        Pattern p = Pattern.compile(reg_charset);        Matcher m = p.matcher(source);        boolean hasChinese = false;        while (m.find()) {            if (!"".equals(m.group(1))) {                hasChinese = true;            }        }        return hasChinese;    }    /**     * 用户名规则判断     *      * @param uname     * @return     */    public static boolean isAccountStandard(String uname) {        Pattern p = Pattern.compile("[A-Za-z0-9_]+");        Matcher m = p.matcher(uname);        return m.matches();    }    // java 合并两个byte数组    public static byte[] byteMerger(byte[] byte_1, byte[] byte_2) {        byte[] byte_3 = new byte[byte_1.length + byte_2.length];        System.arraycopy(byte_1, 0, byte_3, 0, byte_1.length);        System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length);        return byte_3;    }}

2、常用的Log方法LogCat

public class LogCat {    private static final boolean DEBUG = true;    private static final String TAG = "TAG";    public static void v(String msg){        if (DEBUG) {            android.util.Log.v(TAG, msg);        }    }    public static void v(String tag, String msg) {        if (DEBUG) {            android.util.Log.v(tag, msg);        }    }    public static void v(String tag, String msg, Throwable tr) {        if (DEBUG) {            android.util.Log.v(tag, msg, tr);        }    }    public static void d(String msg) {        if (DEBUG) {            android.util.Log.d(TAG, msg);        }    }    public static void d(String tag, String msg) {        if (DEBUG) {            android.util.Log.d(tag, msg);        }    }    public static void d(String tag, String msg, Throwable tr) {        if (DEBUG) {            android.util.Log.d(tag, msg, tr);        }    }    public static void i(String msg) {        if (DEBUG) {            android.util.Log.i(TAG, msg);        }    }    public static void i(String tag, String msg) {        if (DEBUG) {            android.util.Log.i(tag, msg);        }    }    public static void i(String tag, String msg, Throwable tr) {        if (DEBUG) {            android.util.Log.i(tag, msg, tr);        }    }    public static void w(String msg) {        if (DEBUG) {            android.util.Log.w(TAG, msg);        }    }    public static void w(String tag, String msg) {        if (DEBUG) {            android.util.Log.w(tag, msg);        }    }    public static void w(String tag, String msg, Throwable tr) {        if (DEBUG) {            android.util.Log.w(tag, msg, tr);        }    }    public static void w(String tag, Throwable tr) {        if (DEBUG) {            android.util.Log.w(tag, tr);        }    }    public static void e(String msg) {        if (DEBUG) {            android.util.Log.e(TAG, msg);        }    }    public static void e(String tag, String msg) {        if (DEBUG) {            android.util.Log.e(tag, msg);        }    }    public static void e(String tag, String msg, Throwable tr) {        if (DEBUG) {            android.util.Log.e(tag, msg, tr);        }    }}

3、常用的网络方法NetworkUtils

public class NetworkUtils {    public static  boolean mNetWorkState;      public static  boolean NETWORN_NONE=false ;  //  public static  boolean NETWORN_WIFI=false ;      public static  boolean NETWORN_MOBILE;    public static boolean isWifiConnected(Context context) {         boolean network_wifi=false;        if (context != null) {              ConnectivityManager mConnectivityManager = (ConnectivityManager) context                      .getSystemService(Context.CONNECTIVITY_SERVICE);              NetworkInfo mWiFiNetworkInfo = mConnectivityManager                      .getNetworkInfo(ConnectivityManager.TYPE_WIFI);              if (mWiFiNetworkInfo != null) {                  network_wifi= mWiFiNetworkInfo.isAvailable();              }          }          return network_wifi;      }    public boolean isMobileConnected(Context context) {        NETWORN_MOBILE=false;        if (context != null) {              ConnectivityManager mConnectivityManager = (ConnectivityManager) context                      .getSystemService(Context.CONNECTIVITY_SERVICE);              NetworkInfo mMobileNetworkInfo = mConnectivityManager                      .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);              if (mMobileNetworkInfo != null) {                  NETWORN_MOBILE= mMobileNetworkInfo.isAvailable();              }          }          return NETWORN_MOBILE;      }    public static int getConnectedType(Context context) {          if (context != null) {              ConnectivityManager mConnectivityManager = (ConnectivityManager) context                      .getSystemService(Context.CONNECTIVITY_SERVICE);              NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();              if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {                  return mNetworkInfo.getType();              }          }          return -1;      }     private boolean checkNetworkState(Context context) {        mNetWorkState = false;        //得到网络连接信息        ConnectivityManager mConnectivityManager  = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);        //去进行判断网络是否连接        if (mConnectivityManager.getActiveNetworkInfo() != null) {            mNetWorkState = mConnectivityManager.getActiveNetworkInfo().isAvailable();        }        return mNetWorkState; }}

4、常用的文件方法CacheFileUtil

public class CacheFileUtil {    /** 1秒超时时间 */      public static final int CONFIG_CACHE_SHORT_TIMEOUT=1000 * 60 * 5; // 5 分钟      /** 5分钟超时时间 */      public static final int CONFIG_CACHE_MEDIUM_TIMEOUT=1000 * 3600 * 2; // 2小时      /** 中长缓存时间 */      public static final int CONFIG_CACHE_ML_TIMEOUT=1000 * 60 * 60 * 24 * 1; // 1天      /** 最大缓存时间 */      public static final int CONFIG_CACHE_MAX_TIMEOUT=1000 * 60 * 60 * 24 * 7; // 7天      public static final String cacheName = "TVSmall2";    public static final int CONFIG_CACHE_WIFI_TIMEOUT    = 300000;   //5 minute  wifi环境下的缓存时间设置为5分钟    public static final int CONFIG_CACHE_MOBILE_TIMEOUT  = 3600000;  //1 hour    移动数据流量下的缓存时间设置为1小时    public  void setDataCacheFile(String result,String filename,String time){        try {            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){                 File sdCardDir = Environment.getExternalStorageDirectory(); //获取SDCard目录                      File saveFile = new File(sdCardDir+File.separator+cacheName,time+filename);                removeExpiredCache(sdCardDir+File.separator+cacheName,time+filename);  //设置缓存文件时间为1天                if (!saveFile.getParentFile().exists()) {                    saveFile.getParentFile().mkdirs();                 }                FileOutputStream outStream = new FileOutputStream(saveFile);                outStream.write(result.getBytes());                outStream.close();            }        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }    public  String getCacheDate(String filename,String time){        String result = null;        File file = new File(Environment.getExternalStorageDirectory()+File.separator+cacheName,time+filename);        if (file.exists() && file.isFile()) {             long expiredTime = System.currentTimeMillis() - file.lastModified();             if(NetworkUtils.mNetWorkState==false){  //无网络                 result =readTextFile(file);             }else{                 if(NetworkUtils.NETWORN_WIFI==true&& expiredTime>CONFIG_CACHE_WIFI_TIMEOUT){                      return null;                 }else if(NetworkUtils.NETWORN_NONE==true&& expiredTime>CONFIG_CACHE_MOBILE_TIMEOUT){                     return null;                 }             }             result =readTextFile(file);        }        return result;    }    public  String readTextFile(File file) {         StringBuffer sb = new StringBuffer();          try {              BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));               FileInputStream fis = new FileInputStream(file);              int c;              while ((c = br.read()) != -1) {                     sb.append((char) c);              }              br.close();          } catch (FileNotFoundException e) {              e.printStackTrace();          } catch (IOException e) {              e.printStackTrace();          }          return sb.toString();     }    public  void writeTextFile(File file, String data) {        PrintStream out = null;        try {            out = new PrintStream(new FileOutputStream(file));            out.print(data.toString());         } catch (FileNotFoundException e) {            e.printStackTrace();        } finally {            if (out != null) {                out.close();             }        }/** * (/data/data/com.xxx.xxx/cache) * * @param context */    public static void cleanInternalCache(Context context) {        deleteFilesByDirectory(context.getCacheDir());    }    /** * (/data/data/com.xxx.xxx/databases) * * @param context */    public static void cleanDatabases(Context context) {        deleteFilesByDirectory(new File("/data/data/"                + context.getPackageName() + "/databases"));    }    /**     * * SharedPreference(/data/data/com.xxx.xxx/shared_prefs) * * @param     * context     */    public static void cleanSharedPreference(Context context) {        deleteFilesByDirectory(new File("/data/data/"                + context.getPackageName() + "/shared_prefs"));    }    /**     * @param context     *            * @param dbName     */    public static void cleanDatabaseByName(Context context, String dbName) {        context.deleteDatabase(dbName);    }    /** /data/data/com.xxx.xxx/files* * @param context */    public static void cleanFiles(Context context) {        deleteFilesByDirectory(context.getFilesDir());    }    /**     * * (/mnt/sdcard/android/data/com.xxx.xxx/cache) * * @param context     */    public static void cleanExternalCache(Context context) {        if (Environment.getExternalStorageState().equals(                Environment.MEDIA_MOUNTED)) {            Log.e("smile", "cleanExternalCache   " + context.getExternalCacheDir());            deleteFilesByDirectory(context.getExternalCacheDir());        }    }    /** @param filePath */    public static void cleanCustomCache(String filePath) {        deleteFilesByDirectory(new File(filePath));    }    /**     * @param context     *            * @param filepath     */    public static void cleanApplicationData(Context context) {        cleanInternalCache(context);        cleanExternalCache(context);        cleanFiles(context);    }    /** @param directory */    private static void deleteFilesByDirectory(File directory) {        if (directory.isFile()) {            directory.delete();            return;        }        if (directory.isDirectory()) {            File[] childFiles = directory.listFiles();            if (childFiles == null || childFiles.length == 0) {                directory.delete();                return;            }            for (int i = 0; i < childFiles.length; i++) {                deleteFilesByDirectory(childFiles[i]);            }            directory.delete();        }    }    public static String getTotalCacheSize(Context context) throws Exception {        long cacheSize = getFolderSize(context.getCacheDir());        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {            cacheSize += getFolderSize(context.getExternalCacheDir());        }        cacheSize += getFolderSize(context.getFilesDir());        return getFormatSize(cacheSize);    }    // 计算某个文件的大小    private static long getFolderSize(File file) throws Exception {        long size = 0;        try {            File[] fileList = file.listFiles();            for (int i = 0; i < fileList.length; i++) {                // 如果下面还有文件                if (fileList[i].isDirectory()) {                    size = size + getFolderSize(fileList[i]);                } else {                    size = size + fileList[i].length();                }            }        } catch (Exception e) {            e.printStackTrace();        }        return size;    }    /**     * 格式化单位     *     * @param size     * @return     */    public static String getFormatSize(double size) {        double kiloByte = size / 1024;        if (kiloByte < 1) {            return "0K";        }        double megaByte = kiloByte / 1024;        if (megaByte < 1) {            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)                    .toPlainString() + "K";        }        double gigaByte = megaByte / 1024;        if (gigaByte < 1) {            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)                    .toPlainString() + "M";        }        double teraBytes = gigaByte / 1024;        if (teraBytes < 1) {            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)                    .toPlainString() + "G";        }        BigDecimal result4 = new BigDecimal(teraBytes);        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()                + "T";    }    }     @SuppressWarnings("unused")    private void removeExpiredCache(String dirPath, String filename) {         File file = new File(dirPath,filename);         if (System.currentTimeMillis() -file.lastModified() > CONFIG_CACHE_ML_TIMEOUT) {             file.delete();         }     }}

5、常用的时间方法TimeUtil

public class TimeUtil {    public static String getCurrentTime() {        return getCurrentTime("yyyy-MM-dd HH:mm:ss");    }    public static String getCurrentTime(String format) {        Date date = new Date();        SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());        String currentTime = sdf.format(date);        return currentTime;    }    public static String getTime(int count) {        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        Calendar c = Calendar.getInstance();        c.add(Calendar.DAY_OF_MONTH, -count);        Date d = c.getTime();        return format.format(d);    }    public static String getTime(int year, int monthOfYear, int dayOfMonth) {        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");        Calendar c = Calendar.getInstance();        c.set(Calendar.YEAR, year);        c.set(Calendar.MONTH, monthOfYear);        c.set(Calendar.DAY_OF_MONTH, dayOfMonth);        Date d = c.getTime();        return format.format(d);    }    public static int getYear(String time) {        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");        Calendar calendar = GregorianCalendar.getInstance();        try {            calendar.setTime(sdf.parse(time));        } catch (ParseException e) {            e.printStackTrace();        }        int year = calendar.get(Calendar.YEAR);        return year;    }    public static int getMonth(String time) {        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");        Calendar calendar = GregorianCalendar.getInstance();        try {            calendar.setTime(sdf.parse(time));        } catch (ParseException e) {            e.printStackTrace();        }        int month = calendar.get(Calendar.MONTH);        return month;    }    public static int getDay(String time) {        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");        Calendar calendar = GregorianCalendar.getInstance();        try {            calendar.setTime(sdf.parse(time));        } catch (ParseException e) {            e.printStackTrace();        }        int day = calendar.get(Calendar.DATE);        return day;    }    /**     * -1:date1大于date2;     * 1:date1小于date2     *     * @param date1     * @param date2     * @return     */    public static int compareDate(String date1, String date2) {        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");        try {            Date dt1 = df.parse(date1);            Date dt2 = df.parse(date2);            if (dt1.getTime() > dt2.getTime()) {                return -1;            } else if (dt1.getTime() < dt2.getTime()) {                return 1;            } else {                return 0;            }        } catch (Exception exception) {            exception.printStackTrace();        }        return 0;    }    /**     * 将millis转换成yyyy-MM-dd     * @param millis     * @return     */    public static String millisToDay(long millis){        SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");        Calendar calendar = Calendar.getInstance();        calendar.setTimeInMillis(millis);        String day = formater.format(calendar.getTime());        return day;    }

6、常用的SharedPreferences方法SaveValueToShared

public class SaveValueToShared {    public static void saveDataToSharedpreference(Context mContext, String spName, String key, Boolean value) {        SharedPreferences sPreferences = mContext.getSharedPreferences(spName, Context.MODE_WORLD_WRITEABLE);        SharedPreferences.Editor editor = sPreferences.edit();        editor.putBoolean(key, value);        editor.commit();    }    public static void saveDataToSharedpreference(Context mContext, String spName, String key, String value){        SharedPreferences sPreferences = mContext.getSharedPreferences(spName, Context.MODE_WORLD_WRITEABLE);        SharedPreferences.Editor editor = sPreferences.edit();        editor.putString(key, value);        editor.commit();    }    public static void saveDataToSharedpreference(Context mContext, String spName, String key, int value){        SharedPreferences sPreferences = mContext.getSharedPreferences(spName, Context.MODE_WORLD_WRITEABLE);        SharedPreferences.Editor editor = sPreferences.edit();        editor.putInt(key, value);        editor.commit();    }    public static void saveDataToSharedpreference(Context mContext, String spName, String key, long value){        SharedPreferences sPreferences = mContext.getSharedPreferences(spName, Context.MODE_WORLD_WRITEABLE);        SharedPreferences.Editor editor = sPreferences.edit();        editor.putLong(key, value);        editor.commit();    }    public static void saveDataToSharedpreference(Context mContext, String spName, String key, float value){        SharedPreferences sPreferences = mContext.getSharedPreferences(spName, Context.MODE_WORLD_WRITEABLE);        SharedPreferences.Editor editor = sPreferences.edit();        editor.putFloat(key, value);        editor.commit();    }    public static Boolean getBooleanValueFromSharedPreference(Context mContext, String spName, String key){        SharedPreferences sPreferences = mContext.getSharedPreferences(spName, Context.MODE_WORLD_READABLE);        return sPreferences.getBoolean(key, false);    }    public static Boolean getBooleanValueFromSharedPreference(Context mContext, String spName, String key,boolean value){        SharedPreferences sPreferences = mContext.getSharedPreferences(spName, Context.MODE_WORLD_READABLE);        return sPreferences.getBoolean(key, value);    }    public static String getStringValueFromSharedPreference(Context mContext, String spName, String key, String value){        SharedPreferences sPreferences = mContext.getSharedPreferences(spName, Context.MODE_WORLD_READABLE);        return sPreferences.getString(key, value);    }    public static int getIntValueFromSharedPreference(Context mContext, String spName, String key, int value){        SharedPreferences sPreferences = mContext.getSharedPreferences(spName, Context.MODE_WORLD_READABLE);        return sPreferences.getInt(key, value);    }    public static long getLongValueFromSharedPreference(Context mContext, String spName, String key, long value){        SharedPreferences sPreferences = mContext.getSharedPreferences(spName, Context.MODE_WORLD_READABLE);        return sPreferences.getLong(key, value);    }    public static float getFloatValueFromSharedPreference(Context mContext, String spName, String key, float value){        SharedPreferences sPreferences = mContext.getSharedPreferences(spName, Context.MODE_WORLD_READABLE);        return sPreferences.getFloat(key, value);    }}
0 0