3:工具类封装(Base64Utils、ToastUtil、SharedPreferencesUtils、GsonTools 、URLEncodeUtils、BytesUtils、DialogUtil...

1:Base64Utils.java

import java.io.UnsupportedEncodingException;

public class Base64Utils {  
      
    private static char[] base64EncodeChars = new char[]  
            { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',  
                    'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',  
                    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5',  
                    '6', '7', '8', '9', '+', '/' };  
    private static byte[] base64DecodeChars = new byte[]  
            { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,  
                    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53,  
                    54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,  
                    12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29,  
                    30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1,  
                    -1, -1, -1 };  
  
    /** 
     * ���� 
     * 
     * @param data 
     * @return 
     */  
    public static String encode(byte[] data)  
    {  
        StringBuffer sb = new StringBuffer();  
        int len = data.length;  
        int i = 0;  
        int b1, b2, b3;  
        while (i < len)  
        {  
            b1 = data[i++] & 0xff;  
            if (i == len)  
            {  
                sb.append(base64EncodeChars[b1 >>> 2]);  
                sb.append(base64EncodeChars[(b1 & 0x3) << 4]);  
                sb.append("==");  
                break;  
            }  
            b2 = data[i++] & 0xff;  
            if (i == len)  
            {  
                sb.append(base64EncodeChars[b1 >>> 2]);  
                sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);  
                sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);  
                sb.append("=");  
                break;  
            }  
            b3 = data[i++] & 0xff;  
            sb.append(base64EncodeChars[b1 >>> 2]);  
            sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);  
            sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);  
            sb.append(base64EncodeChars[b3 & 0x3f]);  
        }  
        return sb.toString();  
    }  
  
    /** 
     * ���� 
     * 
     * @param str 
     * @return 
     */  
    public static byte[] decode(String str)  
    {  
        try  
        {  
            return decodePrivate(str);  
        } catch (UnsupportedEncodingException e)  
        {  
            e.printStackTrace();  
        }  
        return new byte[]  
                {};  
    }  
  
    private static byte[] decodePrivate(String str) throws UnsupportedEncodingException  
    {  
        StringBuffer sb = new StringBuffer();  
        byte[] data = null;  
        data = str.getBytes("US-ASCII");  
        int len = data.length;  
        int i = 0;  
        int b1, b2, b3, b4;  
        while (i < len)  
        {  
  
            do  
            {  
                b1 = base64DecodeChars[data[i++]];  
            } while (i < len && b1 == -1);  
            if (b1 == -1)  
                break;  
  
            do  
            {  
                b2 = base64DecodeChars[data[i++]];  
            } while (i < len && b2 == -1);  
            if (b2 == -1)  
                break;  
            sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));  
  
            do  
            {  
                b3 = data[i++];  
                if (b3 == 61)  
                    return sb.toString().getBytes("iso8859-1");  
                b3 = base64DecodeChars[b3];  
            } while (i < len && b3 == -1);  
            if (b3 == -1)  
                break;  
            sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));  
  
            do  
            {  
                b4 = data[i++];  
                if (b4 == 61)  
                    return sb.toString().getBytes("iso8859-1");  
                b4 = base64DecodeChars[b4];  
            } while (i < len && b4 == -1);  
            if (b4 == -1)  
                break;  
            sb.append((char) (((b3 & 0x03) << 6) | b4));  
        }  
        return sb.toString().getBytes("iso8859-1");  
    }  
}  

 

2:ToastUtil:

import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.cqsl.pay.R;

/**
 * Toast提示工具类
 * @author baoxl
 *
 */
public class ToastUtil {
    private static final long TOAST_THRESHOLD = 2000;
    private static long previous = 0;
    private static Toast toast;
    private static Context context;
    private static TextView tipTv;

    private ToastUtil() {}
    
    public static void init(Context ctx) {
        context = ctx;
    }

    public static void toast(String message) {
        toast(message, Toast.LENGTH_LONG);
    }

    public static void toast(int id) {
        toast(id, Toast.LENGTH_LONG);
    }

    public static void toast(int id, int duration) {
        String message = context.getString(id);
        toast(message, duration);
    }

    public static void toast(String text, int duration) {
        long now = System.currentTimeMillis();
        if (now - previous < TOAST_THRESHOLD) {
            tipTv.setText(text);
            toast.show();
        } else {
            toast = new Toast(context);
            View view = LayoutInflater.from(context).inflate(R.layout.toast_view, null);
            tipTv = (TextView) view.findViewById(R.id.toast_text);
            tipTv.setText(text);
            toast.setDuration(duration);
            toast.setGravity(Gravity.BOTTOM, 0, 0);
            toast.setView(view);
            toast.show();
        }
        previous = now;
    }
    
    public static void toast(String text, int duration, int xOffset, int yOffset) {
        long now = System.currentTimeMillis();
        if (now - previous < TOAST_THRESHOLD) {
            tipTv.setText(text);
            toast.show();
        } else {
            toast = new Toast(context);
            View view = LayoutInflater.from(context).inflate(R.layout.toast_view, null);
            tipTv = (TextView) view.findViewById(R.id.toast_text);
            tipTv.setText(text);
            toast.setDuration(duration);
            toast.setView(view);
            toast.setGravity(Gravity.NO_GRAVITY, xOffset, yOffset);
            toast.show();
        }
        previous = now;
    }
    
    public static void cancel() {
        if (toast != null) {
            toast.cancel();
        }
    }
}

 

3:SharedPreferencesUtils

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

public class SharedPreferencesUtils {

    public static final String SP_NAME = "config";
    private static SharedPreferences sp;

    /**
     * 保存字符串
     * 
     * @param context
     * @param key
     * @param value
     */
    public static void saveString(Context context, String key, String value) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        sp.edit().putString(key, value).commit();
    }
    

    /**
     * 保存布尔
     * 
     * @param context
     * @param key
     * @param value
     */
    public static void saveBoolean(Context context, String key, boolean value) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        sp.edit().putBoolean(key, value).commit();
    }

    public static void saveInt(Context context, String key, int value) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        sp.edit().putInt(key, value).commit();
    }
    
    public static int getInt(Context context, String key, int defValue) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        return sp.getInt(key, defValue);
    }
    public static void saveFloat(Context context, String key, float value) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        sp.edit().putFloat(key, value).commit();
    }
    public static float getFloat(Context context, String key, float defValue) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        return sp.getFloat(key, defValue);
    }

    /**
     * 返回字符串
     * 
     * @param context
     *            上下文
     * @param key
     *            key
     * @param defValue
     *            默认值
     * @return
     */
    public static String getString(Context context, String key, String defValue) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        return sp.getString(key, defValue);
    }

    public static boolean getBoolean(Context context, String key,
            boolean defValue) {
        if (sp == null)
            sp = context.getSharedPreferences(SP_NAME, 0);
        return sp.getBoolean(key, defValue);
    }
}

 

4:GsonTools

package com.example.c10demo;


import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class GsonTools {

    public GsonTools() {
        // TODO Auto-generated constructor stub
    }

    public static String createGsonString(Object object) {
        Gson gson = new Gson();
        String gsonString = gson.toJson(object);
        return gsonString;
    }

    public static <T> T changeGsonToBean(String gsonString, Class<T> cls) {
        Gson gson = new Gson();
        T t = gson.fromJson(gsonString, cls);
        return t;
    }

    public static <T> List<T> changeGsonToList(String gsonString, Class<T> cls) {
        Gson gson = new Gson();
        List<T> list = gson.fromJson(gsonString, new TypeToken<List<T>>() {
        }.getType());
        return list;
    }

    

    public static <T> List<Map<String, T>> changeGsonToListMaps(
            String gsonString) {
        List<Map<String, T>> list = null;
        Gson gson = new Gson();
        list = gson.fromJson(gsonString, new TypeToken<List<Map<String, T>>>() {
        }.getType());
        return list;
    }

    public static <T> Map<String, T> changeGsonToMaps(String gsonString) {
        Map<String, T> map = null;
        Gson gson = new Gson();
        map = gson.fromJson(gsonString, new TypeToken<Map<String, T>>() {
        }.getType());
        return map;
    }
}

 

 

5:URLEncodeUtils

发送给服务端的请求中的参数值,如果含有特殊符号,需要是做URLEncode,服务端才可以正常解析,否则可能会出错。

URLEncode主要是把一些特殊字符转换成转移字符,比如:&要转换成&amp;这样的。

如果不转换,可能会在运行时直接报错。

如果全部转换,也会报错,因为会把其中非参数的部分也给转换了。

所以要确保只有参数部分被转换。

package com.landicorp.android.util;

import java.net.URLDecoder;
import java.net.URLEncoder;

import android.util.Log;

public class URLEncodeUtils {
    public static String toURLEncoded(String paramString) {  
        if (paramString == null || paramString.equals("")) {  
            Log.d("toURLEncoded error:",paramString);  
            return "";  
        }  
          
        try  
        {  
            String str = new String(paramString.getBytes(), "UTF-8");  
            str = URLEncoder.encode(str, "UTF-8");  
            return str;  
        }  
        catch (Exception localException)  
        {  
            Log.d("toURLEncoded error:",paramString, localException);  
        }  
          
        return "";  
    }  
    
    public static String toURLDecoded(String paramString) {  
        if (paramString == null || paramString.equals("")) {  
            Log.d("toURLDecoded error:",paramString);  
            return "";  
        }  
          
        try  
        {  
            String str = new String(paramString.getBytes(), "UTF-8");  
            str = URLDecoder.decode(str, "UTF-8");  
            return str;  
        }  
        catch (Exception localException)  
        {  
            Log.e("toURLDecoded error:",paramString, localException);  
        }  
          
        return "";  
    }  
}

 

 

5:BytesUtil

import java.io.*;

public class BytesUtil
{

    private BytesUtil()
    {
    }

    public static String bytes2HexString(byte data[])
    {
        StringBuilder buffer = new StringBuilder();
        byte abyte0[];
        int j = (abyte0 = data).length;
        for(int i = 0; i < j; i++)
        {
            byte b = abyte0[i];
            String hex = Integer.toHexString(b & 255);
            if(hex.length() == 1)
                buffer.append('0');
            buffer.append(hex);
        }

        return buffer.toString().toUpperCase();
    }

    public static byte[] hexString2Bytes(String data)
    {
        byte result[] = new byte[(data.length() + 1) / 2];
        if((data.length() & 1) == 1)
            data = (new StringBuilder(String.valueOf(data))).append("0").toString();
        for(int i = 0; i < result.length; i++)
            result[i] = (byte)(hex2byte(data.charAt(i * 2 + 1)) | hex2byte(data.charAt(i * 2)) << 4);

        return result;
    }

    public static byte hex2byte(char hex)
    {
        if(hex <= 'f' && hex >= 'a')
            return (byte)((hex - 97) + 10);
        if(hex <= 'F' && hex >= 'A')
            return (byte)((hex - 65) + 10);
        if(hex <= '9' && hex >= '0')
            return (byte)(hex - 48);
        else
            return 0;
    }

    public static byte[] subBytes(byte data[], int offset, int len)
    {
        if(offset < 0 || data.length <= offset)
            return null;
        if(len < 0 || data.length < offset + len)
            len = data.length - offset;
        byte ret[] = new byte[len];
        System.arraycopy(data, offset, ret, 0, len);
        return ret;
    }

    public static transient byte[] merage(byte data[][])
    {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        byte abyte1[];
        byte abyte0[][];
        int j = (abyte0 = data).length;
        for(int i = 0; i < j; i++)
        {
            byte d[] = abyte0[i];
            if(d == null)
                throw new IllegalArgumentException("");
            buffer.write(d);
        }

        abyte1 = buffer.toByteArray();
        try
        {
            buffer.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        return abyte1;
        IOException e;
        e;
        e.printStackTrace();
        try
        {
            buffer.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        break MISSING_BLOCK_LABEL_117;
        Exception exception;
        exception;
        try
        {
            buffer.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        throw exception;
        return null;
    }

    public static int bytesToInt(byte bytes[])
    {
        if(bytes.length > 4)
            return -1;
        int lastIndex = bytes.length - 1;
        int result = 0;
        for(int i = 0; i < bytes.length; i++)
            result |= (bytes[i] & 255) << (lastIndex - i << 3);

        return result;
    }

    public static int littleEndianBytesToInt(byte bytes[])
    {
        if(bytes.length > 4)
            return -1;
        int result = 0;
        for(int i = 0; i < bytes.length; i++)
            result |= (bytes[i] & 255) << (i << 3);

        return result;
    }

    public static byte[] intToBytes(int intValue)
    {
        byte bytes[] = new byte[4];
        for(int i = 0; i < bytes.length; i++)
            bytes[i] = (byte)(intValue >> (3 - i << 3) & 255);

        return bytes;
    }

    public static byte[] intToLittleEndianBytes(int intValue)
    {
        byte bytes[] = new byte[4];
        for(int i = 0; i < bytes.length; i++)
            bytes[i] = (byte)(intValue >> (i << 3) & 255);

        return bytes;
    }

    public static String bcd2Ascii(byte bcd[])
    {
        if(bcd == null)
            return "";
        StringBuilder sb = new StringBuilder(bcd.length << 1);
        byte abyte0[];
        int j = (abyte0 = bcd).length;
        for(int i = 0; i < j; i++)
        {
            byte ch = abyte0[i];
            byte half = (byte)(ch >> 4);
            sb.append((char)(half + (half <= 9 ? 48 : 55)));
            half = (byte)(ch & 15);
            sb.append((char)(half + (half <= 9 ? 48 : 55)));
        }

        return sb.toString();
    }

    public static byte[] ascii2Bcd(String ascii)
    {
        if(ascii == null)
            return null;
        if((ascii.length() & 1) == 1)
            ascii = (new StringBuilder("0")).append(ascii).toString();
        byte asc[] = ascii.getBytes();
        byte bcd[] = new byte[ascii.length() >> 1];
        for(int i = 0; i < bcd.length; i++)
            bcd[i] = (byte)(hex2byte((char)asc[2 * i]) << 4 | hex2byte((char)asc[2 * i + 1]));

        return bcd;
    }

    public static byte[] toBytes(String data, String charsetName)
    {
        try
        {
            return data.getBytes(charsetName);
        }
        catch(UnsupportedEncodingException e)
        {
            return null;
        }
    }

    public static byte[] toBytes(String data)
    {
        return toBytes(data, "ISO-8859-1");
    }

    public static byte[] toGBK(String data)
    {
        return toBytes(data, "GBK");
    }

    public static byte[] toGB2312(String data)
    {
        return toBytes(data, "GB2312");
    }

    public static byte[] toUtf8(String data)
    {
        return toBytes(data, "UTF-8");
    }

    public static String fromBytes(byte data[], String charsetName)
    {
        try
        {
            return new String(data, charsetName);
        }
        catch(UnsupportedEncodingException e)
        {
            return null;
        }
    }

    public static String fromBytes(byte data[])
    {
        return fromBytes(data, "ISO-8859-1");
    }

    public static String fromGBK(byte data[])
    {
        return fromBytes(data, "GBK");
    }

    public static String fromGB2312(byte data[])
    {
        return fromBytes(data, "GB2312");
    }

    public static String fromUtf8(byte data[])
    {
        return fromBytes(data, "UTF-8");
    }

    private static final String CHARSET_ISO8859_1 = "ISO-8859-1";
    private static final String CHARSET_GBK = "GBK";
    private static final String CHARSET_GB2312 = "GB2312";
    private static final String CHARSET_UTF8 = "UTF-8";
}

 

6:DialogUtil

package com.landicorp.android.util;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.TextView;

public final class DialogUtil {
    private static final int textSize = 18;
    
    private DialogUtil() {}
    
    public static void showMessage(Context context, String title, String message, final OnConfirmListener listener) {
        AlertDialog dialog = new AlertDialog.Builder(context)
            .setCancelable(false)
//            .setIcon(android.R.drawable.ic_dialog_info)
            .setTitle(title)
            .setMessage(message)
            .setPositiveButton("确    认", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (listener != null) {
                        listener.onConfirm();
                    }
                }
            })
            .create();
        dialog.show();
        setDialogAttribute(dialog, textSize);
        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
    }
    
    public static void showOption(Context context, String title, String message, final OnChooseListener listener) {
        AlertDialog dialog = new AlertDialog.Builder(context)
            .setCancelable(false)
//            .setIcon(android.R.drawable.ic_dialog_info)
            .setTitle(title)
            .setMessage(message)
            .setPositiveButton("确    定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (listener != null) {
                        listener.onConfirm();
                    }
                }
            })
            .setNegativeButton("取    消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (listener != null) {
                        listener.onCancel();
                    }
                }
            })
            .create();
        dialog.show();
        setDialogAttribute(dialog, textSize);
        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
    }
    
    public static void showOption(Context context, String title, String message, final OnConfirmListener listener) {
        AlertDialog dialog = new AlertDialog.Builder(context)
            .setCancelable(false)
//            .setIcon(android.R.drawable.ic_dialog_info)
            .setTitle(title)
            .setMessage(message)
            .setPositiveButton("确    定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (listener != null) {
                        listener.onConfirm();
                    }
                }
            })
            .setNegativeButton("取    消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            })
            .create();
        dialog.show();
        setDialogAttribute(dialog, textSize);
        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
    }
    
    public static void showOption(Context context, String message, final OnConfirmListener listener) {
        showOption(context, "系统提示", message, listener);
    }
    
    public static void showOption(Context context, String message, final OnChooseListener listener) {
        showOption(context, "系统提示", message, listener);
    }
    
    public static void showMessage(Context context, String message) {
        showMessage(context, "系统提示", message, null);
    }
    
    public static void showMessage(Context context, String message, OnConfirmListener listener) {
        showMessage(context, "系统提示", message, listener);
    }
    
    public interface OnChooseListener {
        void onConfirm();
        void onCancel();
    }
    
    public interface OnConfirmListener {
        void onConfirm();
    }

    /**
     * 设置对话框系统字体属性
     * @param dialog
     */
    private static void setDialogAttribute(AlertDialog dialog, int fontSize) {
        WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes();  
        layoutParams.width = LayoutParams.WRAP_CONTENT;
        layoutParams.height = LayoutParams.WRAP_CONTENT;
        dialog.getWindow().setAttributes(layoutParams);
        setDialogFontSize(dialog, fontSize);
    }
    
    private static void setDialogFontSize(Dialog dialog, int size) {
        Window window = dialog.getWindow();
        View view = window.getDecorView();
        setViewFontSize(view, size);
    }

    private static void setViewFontSize(View view, int size) {
        if (view instanceof TextView) {
            TextView textview = (TextView) view;
            textview.setGravity(Gravity.CENTER);
            textview.setTextSize(size);
            textview.getPaint().setFakeBoldText(true);
            return;
        }
        
        if (view instanceof ViewGroup) {
            ViewGroup parent = (ViewGroup) view;
            int count = parent.getChildCount();
            for (int i = 0; i < count; i++) {
                setViewFontSize(parent.getChildAt(i), size);
            }
        }
    }
}

 

转载于:https://www.cnblogs.com/wnpp/p/7817278.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值