Adv

Android Utilities

Android Utilities Tutorial

 

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;

import com.example.jkapp.R;
import com.example.jkapp.activity.MyApplication;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * Created by dufangyu on 2016/7/19.
 * / public class Util {

    /**
     * Get vehicle status
     * @param context
     * @return
     */
//    public static String getCarState(Context context, int position)
//    {
//        String strvalue="";
//        String[] strArr = context.getResources().getStringArray(R.array.statecontent);
//        strvalue = strArr[position];
//        return strvalue;
//
//    }

    /**
     * Get the current date
     * @param date
     * @return
     */
    public static String getToady(Date date)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        return sdf.format(date);
    }

    public static String getToady2(Date date)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    public static String getToady3(Date date)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
        return sdf.format(date);
    }

    /**
     * Get the time within one month of the current date as the end date:
     * @param dateNow
     * @return
     */
    public static String getBeforeMonth(Date dateNow)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dateBefore = new Date();
        Calendar cal = Calendar.getInstance();

        cal.setTime(dateNow);

        cal.add(Calendar.MONTH, -1);

        dateBefore = cal.getTime();

        return sdf.format(dateBefore);
    }

    /**
     *
     * Get the day before the current date
     * @param date
     * @return
     */
    public static String getYesterDay(Date date)
    {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DAY_OF_MONTH,-1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cal.getTime());
    }

    /**
     * Get the day before yesterday
     * @param date
     * @return
     */
    public static String getQianTianDay(Date date)
    {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DAY_OF_MONTH,-2);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cal.getTime());
    }

    /**
     * Get the day after the date
     * @param date
     * @return
     */
    public static String getTomorrowDay(Date date)
    {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DAY_OF_MONTH,1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cal.getTime());
    }

    /**
     * the difference between the two times
     */

    public static String differBetweenDates(String starttime, String endtime)
    {
        String result="";
//        LogUtil.d("dfy", "startTime = " + starttime);
//        LogUtil.d("dfy", "endtime = " + endtime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date startDate = sdf.parse(starttime);
            Date endDate =Sdf . parse ( endtime ); long nd = 1000 * 24 * 60 * 60 ; long nh = 1000 * 60 * 60 ; long nm = 1000 * 60 ; long ns = 1000 ; // get the difference in milliseconds between two times long Diff = endDate . getTime () - startDate . getTime (); // Calculate how many days difference

            Long day = diff / nd ; // Calculate how many hours difference long hour = diff % nd / nh ; // Calculate how many minutes difference long min = diff % nd % nh / nm ; // Calculate how many seconds difference / / output result long Sec = diff % nd % nh % nm / ns ;

//            result =hour + "小时" + min + "分钟"+ sec + "秒";
//            LogUtil.d("dfy","diff = "+diff);

            /**
             * Round up: Math.ceil () / / as long as there are decimals +1
             Round down: Math.floor() //Do not take decimals
             Rounding: Math.round() //rounding**/ 
            result = Math . round ( Math . ceil (( float ) diff / nm ))+ "minutes " ; } catch ( ParseException e ) {

        }
        return result;
    }

    //两个时间相差多少天
    public static String differDaysBetweenDates(String starttime, String endtime)
    {
        String result="";
//        LogUtil.d("dfy", "startTime = " + starttime);
//        LogUtil.d("dfy", "endtime = " + endtime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date startDate = sdf.parse(starttime);
            Date endDate = sdf . parse ( endtime ); long nd = 1000 * 24 * 60 * 60 ; long nh = 1000 * 60 * 60 ; long nm = 1000 * 60 ; long ns = 1000 ; // get the difference in milliseconds between two times Long diff = endDate . getTime () - startDate . getTime (); // Calculate how many days difference

            Long day = diff / nd ; // Calculate how many hours difference long hour = diff % nd / nh ; // Calculate how many minutes difference long min = diff % nd % nh / nm ; // Calculate how many seconds difference / / output result long Sec = diff % nd % nh % nm / ns ;

//            result =hour + "小时" + min + "分钟"+ sec + "秒";
//            LogUtil.d("dfy","day = "+day);
            result =day+"";
        } catch (ParseException e) {

        }
        return result;
    }

    public static String getHour(float value)
    {
        String result="";
        try {
            int time = (int)value;
            int hour = time/60;
            result =hour+"时";
        } catch (Exception e) {

        }
        return result;
    }

    public static String getMin(float value)
    {
        String result="";
        try {
            int time = (int)value;

            int min = time%60;
            result =min+"分";
        } catch (Exception e) {

        }
        return result;
    }

    public static String getWorkTime(long worktime )
    {
        String result="";

        Long time = worktime * 1000 ; long nd = 1000 * 24 * 60 * 60 ; long nh = 1000 * 60 * 60 ; long nm = 1000 * 60 ; long ns = 1000 ; // how many days to calculate the difference long day = time / Nd ; // Calculate how many hours difference long hour = time %

        Nd / nh ; // Calculate how many minutes difference long min = time % nd % nh / nm ; // Calculate how many seconds difference // output result long sec = time % nd % nh % nm / ns ; 
        result = hour + "hour " + min + "minutes " + sec + "seconds " ; return result ; }

    public static boolean isValidToken()
    {
        long resultTime=0;

        long logintime = MyApplication.getInstance().getLongPerference("logintime");

        long curenttime = System.currentTimeMillis();
        resultTime = curenttime-logintime;
        long nm = 1000 * 60;
        long min = resultTime/nm;
        LogUtil.d("dfy","min = "+min);
        int diff = (int)min;
        LogUtil.d("dfy","diff = " + diff ); if ( diff > Constant . TOKENTIME ) //more than 10 minutes, token expires { return true ; } return false ; }

    public static void sendLocalBroadcast(Context context, Intent localIntent) {
        LocalBroadcastManager.getInstance(context).sendBroadcast(localIntent);
    }
    public static int getScreenHeight(Activity context) {
        DisplayMetrics dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;
    }

    public static String stringFilterForLetterNdNumber(String str)throws PatternSyntaxException {
        // 只允许字母和汉字
        String   regEx  =  "[^a-zA-Zu4E00-u9FA5]";
        Pattern p   =   Pattern.compile(regEx);
        Matcher m   =   p.matcher(str);
        return   m.replaceAll("").trim();
    }

    Public static String stringFilter ( String str ) throws PatternSyntaxException { // Only letters, numbers, and Chinese characters String    regEx   = "[^a-zA-Z0-9u4E00-u9FA5]" ; Pattern    p    = Pattern . compile ( regEx ) ; Matcher    m    =    P . Matcher ( STR ); return    m . the replaceAll ( "" ). TRIM (); } public static   

      String stringFilterForText(String str)throws PatternSyntaxException{
        // 只允许汉字
        String   regEx  =  "[^u4E00-u9FA5]";
        Pattern   p   =   Pattern.compile(regEx);
        Matcher   m   =   p.matcher(str);
        return   m.replaceAll("").trim();
    }

    /**
     * Regular expression: verify username
     */
    public static final String REGEX_USERNAME = "^[a-zA-Z]w{5,17}$";

    /**
     * Regular expression: verify password
     */
    public static final String REGEX_PASSWORD = "^[a-zA-Z0-9]{6,16}$";

    /**
     * Regular expression: verify phone number
     */
//    public static final String REGEX_MOBILE = "^((13[0-9])|(15[^4,D])|(18[0,5-9]))d{8}$";
//    public static final String REGEX_MOBILE = "^(0|86|17951)?(13[0-9]|15[0-35-9]|17[0136-8]|18[0-9]|14[579])[0-9]{8}$";
    public static final String REGEX_MOBILE = "^1(3[0-9]|4[579]|5[0-35-9]|7[0136-8]|8[0-9])d{8}$";
    /**
     * Regular expression: verify the mailbox
     */
    public static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?.)+[a-zA-Z]{2,}$";

    /**
     * Regular expression: verify Chinese characters
     */
    public static final String REGEX_CHINESE = "^[u4e00-u9fa5],{0,}$";

    /**
     * Regular expression: verify ID card
     */
    public static final String REGEX_ID_CARD = "(d{14}[0-9a-zA-Z])|(d{17}[0-9a-zA-Z])";

    /**
     * Regular expression: verify URL
     */
//    public static final String REGEX_URL = "http(s)?://([w-]+.)+[w-]+(/[w- ./?%&=]*)?";
    public static final String REGEX_URL = "http://([w-]+.)+[w-]+(/[w - ./?%&=]*)?";

    /**
     * Regular expression: verify IP address
     */
    public static final String REGEX_IP_ADDR = "(25[0-5]|2[0-4]d|[0-1]d{2}|[1-9]?d)";

    /**
     * Verify user name
     *
     *  username
     * Validation returns true, otherwise returns false
     */
    public static boolean isUsername(String username) {
        return Pattern.matches(REGEX_USERNAME, username);
    }

    /**
     * Verify password
     *
     *  password
     * Validation returns true, otherwise returns false
     */
    public static boolean isPassword(String password) {
        return Pattern.matches(REGEX_PASSWORD, password);
    }

    /**
     * Verify phone number
     *
     *  mobile
     * Validation returns true, otherwise returns false
     */
    public static boolean isMobile(String mobile) {
        return Pattern.matches(REGEX_MOBILE, mobile);
    }

    /**
     * Verify the mailbox
     *
     *  email
     * Validation returns true, otherwise returns false
     */
    public static boolean isEmail(String email) {
        return Pattern.matches(REGEX_EMAIL, email);
    }

    /**
     * Verify Chinese characters
     *
     *  chinese
     * Validation returns true, otherwise returns false
     */
    public static boolean isChinese(String chinese) {
        return Pattern.matches(REGEX_CHINESE, chinese);
    }

    /**
     * Verify ID card
     *
     *  idCard
     * Validation returns true, otherwise returns false
     */
    public static boolean isIDCard(String idCard) {
        return Pattern.matches(REGEX_ID_CARD, idCard);
    }

    /**
     * Verify URL
     *
     *  url
     * Validation returns true, otherwise returns false
     */
    public static boolean isUrl(String url) {
        return Pattern.matches(REGEX_URL, url);
    }

    /**
     * Verify IP address
     *
     *  ipAddr
     *
     */
    public static boolean isIPAddr(String ipAddr) {
        return Pattern.matches(REGEX_IP_ADDR, ipAddr);
    }

    public static String getReportDate(String str)
    {
        String[] strArr = str.split(" ");
        if(strArr!=null && strArr.length>0)
            return strArr[0];
        return "";
    }
    public static String getReportTime(String str)
    {
        if(!TextUtils.isEmpty(str))
        {
            String[] strArr = str.split(" ");
            if(strArr!=null && strArr.length>0)
                return strArr[1];

        }
        return "";
    }

    public static void writeObject ( String key , Object obj ) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream (); ObjectOutputStream east = new ObjectOutputStream ( baos ); 
            east . writeObject ( obj ); String objBase64 = new String ( Base64 . Encode ( baos .    

              toByteArray(),Base64.DEFAULT));
            MyApplication.getInstance().setStringPerference(key, objBase64);
        } catch (Exception e) {
            Log.e("test", "saveObject error", e);
        }
    }

    public static Object readObject(String key) {
        try {
//            String objBase64 = getPreference(ctx).getString(key, null);
            String objBase64 = MyApplication.getInstance().getStringPerference(key);
            if (TextUtils.isEmpty(objBase64)) {
                return null;
            }
            byte[] base64 = Base64.decode(objBase64,Base64.DEFAULT);
            ByteArrayInputStream bais = new ByteArrayInputStream(base64);
            ObjectInputStream bis = new ObjectInputStream(bais);
            return bis.readObject();
        } catch (Exception e) {
            Log.e("test", "readObject error", e);
        }
        return null;
    }

    /**
     * Is there Chinese?
     * @param str
     * @return
     */
    public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[u4e00-u9fa5]");
        Matcher m = p.matcher(str);
        return m.find();
    }
    /**
     * Determine if the string contains letters
     *
     * @param str
     * @return
     */
    public static boolean isContainLetters(String str) {
        for (char i = 'A'; i <= 'Z'; i++) {
            if (str.contains(String.valueOf(i))) {
                return true;
            }
        }
        for (char i = 'a'; i <= 'z'; i++) {
            if (str.contains(String.valueOf(i))) {
                return true;
            }
        }
        return false;
    }

    public static String getGroupValue(String oldStr,String newStr)
    {
        StringBuffer sb = new StringBuffer();
        sb.append(oldStr).append("|").append(newStr);
        return sb.toString();
    }

    public static String getMuShuValue(Object value)
    {
        DecimalFormat numberFormat = new DecimalFormat("0.0");
        return numberFormat.format(value);
    }

    public static void SystemMsg(Context  context, String strTitle, String strMsg) {
        // 信息提示
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setIcon(android.R.drawable.ic_dialog_info);
        if (strTitle != "") {
            builder.setTitle("系统提示");
        }
        builder.setMessage(strMsg);
        builder.setPositiveButton("确认", null);
        builder.create().show();
    }

    public static AlertDialog alterDialog(Context context,View view){
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setView(view);
        AlertDialog dialog = builder.show();
        dialog.setCancelable(false);
        Window window=dialog.getWindow();
        window.setGravity(Gravity.CENTER);
        window.setWindowAnimations(R.style.popwinAnim);
        return dialog;
    }

    /**
     *
     * @param min
     * @param max
     * @return
     */
    public static int getRandomValue(int min,int max)
    {
//        Random random = new Random();
//        int value = random.nextInt(max+1);//返回[0,max]
//        return value;

        return (int)(min+Math.random()*(max-min+1));
    }

}

Share
Adv



Share an Example

Share an Example

Browse
What is the capital of Egypt? ( Cairo )