Android 小工具

package zzm.wdys.cloudbackup.utils;

import android.app.Dialog;
import android.content.Context;
import android.view.View;

public class DialogUtil {

    /*获取到弹窗,设置它的属性,大小,自定义的布局,和监听器等*/
    public static Dialog getDialog(Context c, int layoutResID, int styleResID,
                                   boolean isCancelable, boolean isCanceledOnTouchOutside,
                                   DialogSizeListenerItf dialogSizeListenerItf) {

        // 得到加载view
        View v = View.inflate(c, layoutResID, null);

        //创建自定义样式dialog
        Dialog dialog = new Dialog(c, styleResID);

        //设置按返回键是否隐藏弹窗
        dialog.setCancelable(isCancelable);

        //设置点击 dialog 外是否 隐藏 弹窗
        dialog.setCanceledOnTouchOutside(isCanceledOnTouchOutside);

        //必须设置 dialog 自定义的 布局 和 大小 以及监听
        dialogSizeListenerItf.settings(v, dialog);

        return dialog;

    }

    /*设置dialog 的尺寸,和 布局上控件的 点击监听事件,文案等等*/
    public interface DialogSizeListenerItf {

        void settings(View v, Dialog dialog);

    }

}
package zzm.wdys.cloudbackup.utils;

import android.content.Context;
import android.content.SharedPreferences;

public class LocalStoreUtil {

    /*SP  存储 数据*/
    public static void spStore(Context c, String xmlName, String storeData, String storeDataKey) {

        SharedPreferences sp = c.getSharedPreferences(xmlName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(storeDataKey, storeData);
        if (!editor.commit()) {
            LogUtil.log("存储本地数据" + storeDataKey + "失败");
        } else {
        }

    }

    /*sp得到本地存储数据*/
    public static String spGetStoreData(Context c, String xmlName, String storeDataKey) {

        SharedPreferences sp = c.getSharedPreferences(xmlName, Context.MODE_PRIVATE);
        String storeData = sp.getString(storeDataKey, "");
        if ("".equals(storeData) || null == storeData) {

            LogUtil.log("获取本地数据" + storeDataKey + "失败");

            return "";

        } else {
        }
        return storeData;

    }

    /*sp清除数据*/
    public static void spClearStoreData(Context c, String xmlName, boolean isClearAll, String storeDataKey) {

        SharedPreferences sp = c.getSharedPreferences(xmlName, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        if (isClearAll) {
            editor.clear();
        } else {
            editor.remove(storeDataKey);
        }

        if (editor.commit()) {
        } else {
            LogUtil.log("  清除数据失败---xml" + xmlName + "   key : " + storeDataKey);
        }

    }

}
package zzm.wdys.cloudbackup.utils;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;

import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;

import java.util.Locale;
import java.util.UUID;


/**
 * 该类有
 * 1.屏幕的宽高度
 * 2.还有状态栏的高度
 * 3.设置状态栏颜色
 * 4.键盘的操作
 * 6.获取设备唯一id
 * 8.dp 转换成 px
 * 11.获取手机的 国家代码
 */

public class PhoneUtil {

    /*1.获取设备id*/
    public static String getDeviceID(Context c) {

        String serial;
        String m_szDevIDShort = "35" + (Build.BOARD.length() % 10) +
                (Build.BRAND.length() % 10) +
                (Build.CPU_ABI.length() % 10) +
                (Build.DEVICE.length() % 10) +
                (Build.MANUFACTURER.length() % 10) +
                (Build.MODEL.length() % 10) +
                (Build.PRODUCT.length() % 10);

        try {
            serial = android.os.Build.class.getField("SERIAL").get(null).toString();
        } catch (Exception e) {
            serial = "serial";
        }
        String uuid = new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        return uuid;

    }

    /*2.获取国家代码*/
    public static String getCountryCode(Context c) {

        String countryCode;

        Locale locale = c.getResources().getConfiguration().locale;

        countryCode = locale.getCountry();

        return countryCode;
    }

    /*3.屏幕物理宽度*/
    public static int getPhoneWidthPixels(Context c) {

        WindowManager wm = (WindowManager) c
                .getSystemService(Context.WINDOW_SERVICE);

        return wm.getDefaultDisplay().getWidth();

    }

    /*3.屏幕物理高度*/
    public static int getPhoneHeightPixels(Context c) {

        WindowManager wm = (WindowManager) c
                .getSystemService(Context.WINDOW_SERVICE);

        return wm.getDefaultDisplay().getHeight();

    }

    /*4.状态栏高度*/
    public static int getStatusBarHeight(Context context) {

        int statusHeight = 0;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height")
                    .get(object).toString());
            statusHeight = context.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            LogUtil.log(e.toString());
        }
        return statusHeight;

    }


    /*5.dp to px*/
    public static int dp2px(Activity c, int dp) {

        DisplayMetrics metrics = new DisplayMetrics();

        c.getWindowManager().getDefaultDisplay().getMetrics(metrics);

        int youNeedPx = (int) (metrics.density * dp + 0.5f);

        return youNeedPx;
    }

    /*9.手机键盘的操作*/

    /**
     * 如果当前键盘已经显示,则隐藏
     * 如果当前键盘未显示,则显示
     *
     * @param context
     */
    public static void toggleSoftInput(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 弹出键盘
     *
     * @param context
     * @param view
     */
    public static void showSoftInput(Context context, View view) {
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(view, 0);
        }
    }

    /**
     * 隐藏键盘
     *
     * @param context
     * @param view
     */
    public static void hideSoftInput(Context context, View view) {
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 获取软键盘的高度 * *
     *
     * @param
     * @param
     */
    public interface OnGetSoftHeightListener {
        void onShowed(int height);
    }

    public interface OnSoftKeyWordShowListener {
        void hasShow(boolean isShow);
    }


    public static void getSoftKeyboardHeight(final View rootView, final OnGetSoftHeightListener listener) {
        final ViewTreeObserver.OnGlobalLayoutListener layoutListener
                = new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (true) {
                    final Rect rect = new Rect();
                    rootView.getWindowVisibleDisplayFrame(rect);
                    final int screenHeight = rootView.getRootView().getHeight();
                    final int heightDifference = screenHeight - rect.bottom;
                    //设置一个阀值来判断软键盘是否弹出
                    boolean visible = heightDifference > screenHeight / 3;
                    if (visible) {
                        if (listener != null) {
                            listener.onShowed(heightDifference);
                        }
                        rootView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    }
                }
            }
        };
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);
    }

    /**
     * 判断软键盘是否弹出
     * * @param rootView
     *
     * @param listener 备注:在不用的时候记得移除OnGlobalLayoutListener
     */
    public static ViewTreeObserver.OnGlobalLayoutListener doMonitorSoftKeyWord(final View rootView, final OnSoftKeyWordShowListener listener) {
        final ViewTreeObserver.OnGlobalLayoutListener layoutListener = () -> {
            final Rect rect = new Rect();
            rootView.getWindowVisibleDisplayFrame(rect);
            final int screenHeight = rootView.getRootView().getHeight();
            final int heightDifference = screenHeight - rect.bottom;
            boolean visible = heightDifference > screenHeight / 3;
            if (listener != null)
                listener.hasShow(visible);
        };
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);
        return layoutListener;
    }

    /*10.状态栏的颜色设置*/
    public static void setStatusBarColor(AppCompatActivity activity, String color) {

        //设置透明
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = activity.getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = activity.getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            ViewGroup decorView = (ViewGroup) activity.findViewById(android.R.id.content);

            //自定义的view覆盖状态栏
            View view = new View(activity);
            view.setBackgroundColor(Color.parseColor(color));
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    PhoneUtil.getStatusBarHeight(activity));
            decorView.addView(view, params);
        }
    }

    /*震动*/
    public static void vibrator(Context c, long timesInMillis) {

        Vibrator vibrator = (Vibrator) c.getSystemService(Service.VIBRATOR_SERVICE);

        vibrator.vibrate(350);

    }

}
package zzm.wdys.cloudbackup.utils;

import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.kyleduo.switchbutton.SwitchButton;

import zzm.wdys.cloudbackup.R;

public class PopWindowUtil {

    //弹出popupwindow
    public static PopupWindow showPhotoAlbumMoreOperatePopWindow(final AppCompatActivity a, View.OnClickListener onClickListener, ViewOperateCallBack viewOperateCallBack) {
        View popView = View.inflate(a, R.layout.photo_more_operate_pop_window_layout, null);
        View delete = popView.findViewById(R.id.delete_tv);
        View rename = popView.findViewById(R.id.rename_tv);
        TextView photoAlbumName = popView.findViewById(R.id.photo_album_name_tv);
        SwitchButton switchButton = popView.findViewById(R.id.switch_button);
        View close = popView.findViewById(R.id.close_iv);

        //获取屏幕宽高
        int width = PhoneUtil.getPhoneWidthPixels(a);
        int height = PhoneUtil.getPhoneHeightPixels(a) * 373 / 1334;

        final PopupWindow popupWindow = new PopupWindow(popView, width, height);
        popupWindow.setAnimationStyle(android.R.style.Animation_InputMethod);
        popupWindow.setFocusable(true);
        //点击外部popueWindow消失
        popupWindow.setOutsideTouchable(true);

        delete.setOnClickListener(onClickListener);
        close.setOnClickListener(onClickListener);
        rename.setOnClickListener(onClickListener);

        //popupWindow消失屏幕变为不透明
        popupWindow.setOnDismissListener(() -> {
            WindowManager.LayoutParams lp = a.getWindow().getAttributes();
            lp.alpha = 1.0f;
            a.getWindow().setAttributes(lp);
        });

        //popupWindow出现屏幕变为半透明
        WindowManager.LayoutParams lp = a.getWindow().getAttributes();
        lp.alpha = 0.5f;
        a.getWindow().setAttributes(lp);
        popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 0);

        viewOperateCallBack.getViews(switchButton, photoAlbumName);

        return popupWindow;

    }

    /*返回 要操作的 多个 view*/
    public interface ViewOperateCallBack {

        void getViews(View... views);

    }


}
package zzm.wdys.cloudbackup.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class StringUtil {

    /*7.MD5加密*/
    public static String getMD5String(String string) {
        byte[] hash = null;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            LogUtil.log(e.toString());
        } catch (UnsupportedEncodingException e) {
            LogUtil.log(e.toString());
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    /*8.sha 256 加密*/
    public static String getSHA256String(String encryptionString, String secret) {
        //要加密的string key
        String hash = "";
        try {
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
            sha256_HMAC.init(secret_key);
            byte[] b = sha256_HMAC.doFinal(encryptionString.getBytes());
            StringBuilder hs = new StringBuilder();
            String stmp;
            for (int n = 0; b != null && n < b.length; n++) {
                stmp = Integer.toHexString(b[n] & 0XFF);
                if (stmp.length() == 1)
                    hs.append('0');
                hs.append(stmp);
            }
            hash = hs.toString().toLowerCase();
        } catch (Exception e) {
        }
        return hash;
    }


}
package zzm.wdys.cloudbackup.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class TimeUtil {

    /*12.根据系统的毫秒数来得到时间的字符串形式*/
    public static String getTimeStr(long timeInMillis) {

        Calendar calendar = new GregorianCalendar();
        calendar.setTimeInMillis(timeInMillis);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);//24小时制
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        String dayStr = day + "";
        String monthStr = ++month + "";
        String hourStr = hour + "";
        String minuteStr = minute + "";
        String secondStr = second + "";

        if (day < 10)
            dayStr = "0" + day;

        if (month < 10)
            monthStr = "0" + month;


        if (minute < 10)
            minuteStr = "0" + minute;

        if (hour < 10)
            hourStr = "0" + hour;

        if (second < 10)
            secondStr = "0" + second;

        return monthStr + "/" + dayStr + "/" + year + " " + hourStr + ":" + minuteStr + ":" + secondStr + "";
    }

    /*12.根据毫秒数获取 01 hours 08  minute  03 seconds的时间字符串格式*/
    public static String getHMSTimeStr(long timeInSecond) {

        String hMSTimeStr;
        long hour = timeInSecond / 3600;
        long mint = (timeInSecond % 3600) / 60;
        long sed = timeInSecond % 60;

        String hourStr = String.valueOf(hour);
        if (hour < 10) {
            hourStr = "0" + hourStr;
        }

        String mintStr = String.valueOf(mint);
        if (mint < 10) {
            mintStr = "0" + mintStr;
        }

        String secondStr = String.valueOf(sed);
        if (sed < 0) {
            secondStr = "0" + secondStr;
        }

        hMSTimeStr = hourStr + " Hours " + mintStr + " Minute" + secondStr + " seconds";

        if (hour == 0)
            hMSTimeStr = mintStr + " Minute" + secondStr + " seconds";

        if (mint == 0 && hour == 0)
            hMSTimeStr = secondStr + " seconds";


        return hMSTimeStr;
    }

    /*12.得到 输入date 获取聊天 那种类似的时间 字符串显示*/
    public static String getTimeStrAccordingNow(Date date) {

        long time = date.getTime();

        if (isThisYear(date)) {//今年

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");

            if (isToday(date)) { //今天

                int minute = minutesAgo(time);

                if (minute < 10) {//1小时之内

                    if (minute < 1) {//一分钟之内,显示刚刚

                        return " Just now";

                    } else {

                        if (minute == 1) {

                            return minute + " Minute ago";

                        } else {

                            return minute + " Minutes ago";

                        }
                    }
                } else {
                    return simpleDateFormat.format(date);
                }
            } else {
                if (isYestYesterday(date)) {//昨天,显示昨天

                    return "Yesterday " + simpleDateFormat.format(date);

                } else if (isThisWeek(date)) {//本周,显示周几

                    String weekday = "";

                    if (date.getDay() == 1) {
                        weekday = "Monday";
                    }
                    if (date.getDay() == 2) {
                        weekday = "Tuesday";
                    }
                    if (date.getDay() == 3) {
                        weekday = "Wednesday";
                    }
                    if (date.getDay() == 4) {
                        weekday = "Thursday";
                    }
                    if (date.getDay() == 5) {
                        weekday = "Friday";
                    }
                    if (date.getDay() == 6) {
                        weekday = "Saturday";
                    }
                    if (date.getDay() == 0) {
                        weekday = "Sunday";
                    }
                    return weekday + " " + simpleDateFormat.format(date);
                } else {
                    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
                    return sdf.format(date);
                }
            }
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return sdf.format(date);
        }
    }

    private static int minutesAgo(long time) {
        return (int) ((System.currentTimeMillis() - time) / (60000));
    }

    private static boolean isToday(Date date) {
        Date now = new Date();
        return (date.getYear() == now.getYear()) && (date.getMonth() == now.getMonth()) && (date.getDate() == now.getDate());
    }

    private static boolean isYestYesterday(Date date) {
        Date now = new Date();
        return (date.getYear() == now.getYear()) && (date.getMonth() == now.getMonth()) && (date.getDate() + 1 == now.getDate());
    }

    private static boolean isThisWeek(Date date) {
        Date now = new Date();
        if ((date.getYear() == now.getYear()) && (date.getMonth() == now.getMonth())) {
            if (now.getDay() - date.getDay() < now.getDay() && now.getDate() - date.getDate() > 0 && now.getDate() - date.getDate() < 7) {
                return true;
            }
        }
        return false;
    }

    private static boolean isThisYear(Date date) {
        Date now = new Date();
        return date.getYear() == now.getYear();
    }

}

猜你喜欢

转载自my.oschina.net/u/2987490/blog/1808002