android 快速开发工具

来源:互联网 发布:dnf强行交易软件 编辑:程序博客网 时间:2024/04/30 13:17

android快速开发的工具类
1、与app相关的辅助类 AppUtils.java

public class AppUtils {    private AppUtils() {        throw new UnsupportedOperationException("connot be instantiated");    }    /**     * 获取应用程序名     */    public static String getAppName(Context context) {        try {            PackageManager packageManager = context.getPackageManager();            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);            int labelRes = packageInfo.applicationInfo.labelRes;            return context.getResources().getString(labelRes);        } catch (PackageManager.NameNotFoundException e) {            e.printStackTrace();        }        return null;    }    /**     * 获取应用程序版本名称信息     * */    public static String getVersionName(Context context){        PackageManager packageManager = context.getPackageManager();        try {            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(),0);            return packageInfo.versionName;        } catch (PackageManager.NameNotFoundException e) {            e.printStackTrace();        }        return null;    }}

2、常用单位转换辅助类 DensityUtils.java

public class DensityUtils {    private DensityUtils() {        throw new UnsupportedOperationException("cannot be instantiated");    }    /**     * dp转px     */    public static int dp2px(Context context, float dpVal) {        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, context.getResources().getDisplayMetrics());    }    /**     * sp转px     */    public static int sp2px(Context context, float spVal) {        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spVal, context.getResources().getDisplayMetrics());    }    /**     * px转dp     */    public static float px2dp(Context context, float pxVal) {        final float scale = context.getResources().getDisplayMetrics().density;        return (pxVal / scale);    }    /**     * px转sp     */    public static float px2sp(Context context, float pxVal) {        return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);    }}

3、图片压缩工具类 ImageCompress.java

public class ImageCompress {    public static Bitmap getBitmap(String filePath) {        BitmapFactory.Options options = new BitmapFactory.Options();        options.inJustDecodeBounds = false;        Bitmap bm = BitmapFactory.decodeFile(filePath, options);        if (bm == null) {            return null;        }        Log.d("zhanglinshu", "");        return bm;    }    public static int getBitmapSize(Bitmap bitmap) {        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {    //API 19            return bitmap.getAllocationByteCount();        }        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {//API 12            return bitmap.getByteCount();        }        return bitmap.getRowBytes() * bitmap.getHeight();                //earlier version    }    public static Bitmap getSmallBitmap(String filePath) {        BitmapFactory.Options options = new BitmapFactory.Options();        options.inJustDecodeBounds = true;        BitmapFactory.decodeFile(filePath, options);        //Calculate insampleSize        options.inSampleSize = calculateInSampleSize(options, 480, 800);        //Decode bitmap with inSampleSize set        options.inJustDecodeBounds = false;        Bitmap bm = BitmapFactory.decodeFile(filePath, options);        if (bm == null) {            return null;        }        int degree = readPictureDegree(filePath);        bm = rotateBitmap(bm, degree);        ByteArrayOutputStream baos = null;        try {            baos = new ByteArrayOutputStream();            bm.compress(Bitmap.CompressFormat.JPEG, 70, baos);            int size = baos.toByteArray().length/1024;        } catch (Exception e) {            e.printStackTrace();        } finally {            if (baos != null) {                try {                    baos.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }        return bm;    }    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {        //Raw height and width of image        int height = options.outHeight;        int width = options.outWidth;        int inSampleSize = 1;        if (height > reqHeight || width > reqHeight) {            int heightRatio = Math.round((float) height / (float) reqHeight);            int widthRatio = Math.round((float) height / (float) reqHeight);            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;        }        return inSampleSize;    }    private static Bitmap rotateBitmap(Bitmap bm, int rotate) {        if (bm == null) {            return null;        }        int w = bm.getWidth();        int h = bm.getHeight();        //setting post rotate to 90        Matrix mtx = new Matrix();        mtx.postRotate(rotate);        return Bitmap.createBitmap(bm, 0, 0, w, h, mtx, true);    }    private static int readPictureDegree(String filePath) {        int degree = 0;        try {            ExifInterface exifInterface = new ExifInterface(filePath);            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);            switch (orientation) {                case ExifInterface.ORIENTATION_ROTATE_90:                    degree = 90;                    break;                case ExifInterface.ORIENTATION_ROTATE_180:                    degree = 180;                    break;                case ExifInterface.ORIENTATION_ROTATE_270:                    degree = 270;                    break;            }        } catch (IOException e) {            e.printStackTrace();        } finally {        }        return degree;    }}

4、软键盘辅助类 KeyBoardUtils.java

public class KeyBoardUtils {    /**     * 打开软件盘     */    public static void openKeybord(EditText mEditText, Context mContext) {        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);        imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);    }    /**     * 关闭软键盘     */    public static void closeKeybord(EditText mEditText, Context mContext) {        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);        imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);    }}

5、日志辅助类 LogUtils.java

public class LogUtils {    private static final String TAG = "zhanglinshu";    public static boolean isDebug = true; //是否打印调试信息    private LogUtils(){        throw new UnsupportedOperationException("connot be instantiated");    }    public static void i(String msg) {        if (isDebug) {            Log.i(TAG, msg);        }    }    public static void d(String msg) {        if (isDebug) {            Log.d(TAG, msg);        }    }    public static void v(String msg) {        if (isDebug) {            Log.v(TAG, msg);        }    }    public static void e(String msg) {        if (isDebug) {            Log.e(TAG, msg);        }    }}

6、MD5加密辅助类 MD5Utils.java

public class MD5Utils {    public static String getMD5(String str) {        byte[] hash;        try {            hash = MessageDigest.getInstance("MD5").digest(str.getBytes("UTF-8"));        } catch (NoSuchAlgorithmException e) {            throw new RuntimeException("Huh, MD5 should be supported?", e);        } catch (UnsupportedEncodingException e) {            throw new RuntimeException("Huh, UTF-8 should be supported?", e);        }        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();    }}

7、网络辅助工具类 NetWorkUtils.java

public class NetWorkUtils {    /**     * 当前网络是否可用     */    public static boolean isNetworkAvailable(Activity activity) {        Context context = activity.getApplicationContext();        // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);        if (connectivityManager == null) {            return false;        } else {            // 获取NetworkInfo对象            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();            if (networkInfo != null && networkInfo.length > 0) {                for (int i = 0; i < networkInfo.length; i++) {                    LogUtils.d(i + "===状态===" + networkInfo[i].getState());                    LogUtils.d(i + "===类型===" + networkInfo[i].getTypeName());                    // 判断当前网络状态是否为连接状态                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {                        return true;                    }                }            }        }        return false;    }}

8、屏幕相关辅助类 ScreenUtils.java

public class ScreenUtils {    private ScreenUtils() {        throw new UnsupportedOperationException("connot be instantiated");    }    /**     * 获取屏幕高度     */    public static int getScreenWidth(Context context) {        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);        DisplayMetrics outMetrics = new DisplayMetrics();        wm.getDefaultDisplay().getMetrics(outMetrics);        return outMetrics.widthPixels;    }    /**     * 获取屏幕宽度     */    public static int getScreenHeight(Context context) {        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);        DisplayMetrics outMetrics = new DisplayMetrics();        wm.getDefaultDisplay().getMetrics(outMetrics);        return outMetrics.heightPixels;    }    /**     * 获取状态栏的高度     */    public static int getStatusHeight(Context context) {        int statueHeight = -1;        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());            statueHeight = context.getResources().getDimensionPixelSize(height);        } catch (ClassNotFoundException e) {            e.printStackTrace();        } catch (InstantiationException e) {            e.printStackTrace();        } catch (IllegalAccessException e) {            e.printStackTrace();        } catch (NoSuchFieldException e) {            e.printStackTrace();        }        return statueHeight;    }    /**     * 获取当前屏幕截图,包含状态栏     */    public static Bitmap snapShotWithStatusBar(Activity activity) {        View view = activity.getWindow().getDecorView();        view.setDrawingCacheEnabled(true);        view.buildDrawingCache();        Bitmap bmp = view.getDrawingCache();        int width = getScreenWidth(activity);        int height = getScreenHeight(activity);        Bitmap bp = null;        bp = Bitmap.createBitmap(bmp, 0, 0, width, height);        view.destroyDrawingCache();        return bp;    }    /**     * 获取当前屏幕截屏,不包含状态栏     */    public static Bitmap snapShotWithoutStatusBar(Activity activity) {        View view = activity.getWindow().getDecorView();        view.setDrawingCacheEnabled(true);        view.buildDrawingCache();        Bitmap bmp = view.getDrawingCache();        Rect frame = new Rect();        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);        int statusBarHeight = frame.top;        int width = getScreenWidth(activity);        int height = getScreenHeight(activity);        Bitmap bp = null;        bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height - statusBarHeight);        view.destroyDrawingCache();        return bp;    }}

9、SD卡辅助类 SDCardUtils.java

public class SDCardUtils {    private SDCardUtils() {        throw new UnsupportedOperationException("cannot be instantiated");    }    /**     * 判断SDCard是否可用     */    public static boolean isSDCardEnable() {        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);    }    /**     * 获取SD卡路径     */    public static String getSDCardPath() {        return Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;    }    /**     * 获取SD卡的剩余容量     */    public static long getSDCardAllSize() {        if (isSDCardEnable()) {            StatFs statFs = new StatFs(getSDCardPath());            //获取空闲的数据块的数量            long availableBlocks = (long) statFs.getAvailableBlocks() - 4;            //获取单个数据块的大小            long freeBlocks = statFs.getAvailableBlocks();            return freeBlocks * availableBlocks;        }        return 0;    }    /**     * 获取指定路径所在控件的剩余可用容量字节数。单位byte     */    public static long getFreeBytes(String filePath) {        //如果是SD卡下的路径,则获取SD卡可用容量        if (filePath.startsWith(getSDCardPath())) {            filePath = getSDCardPath();        } else {            //如果是内部存储路径,则获取内存存储的可用容量            filePath = Environment.getDataDirectory().getAbsolutePath();        }        StatFs stat = new StatFs(filePath);        long availableBlocks = (long) stat.getAvailableBlocks() - 4;        return stat.getBlockSize() * availableBlocks;    }    /**     * 获取系统存储路径     */    public static String getRootDirectoryPath() {        return Environment.getRootDirectory().getAbsolutePath();    }}

10、SharedPreferences封装 SharedPreferencesUtils.java

public class SharedPreferencesUtils {    /**     * 保存在手机里面的文件名     */    public static final String FILE_NAME = "share_data";    /**     * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法     */    public static void put(Context context, String key, Object object) {        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);        SharedPreferences.Editor editor = sp.edit();        if (object instanceof String) {            editor.putString(key, (String) object);        } else if (object instanceof Integer) {            editor.putInt(key, (Integer) object);        } else if (object instanceof Boolean) {            editor.putBoolean(key, (Boolean) object);        } else if (object instanceof Float) {            editor.putFloat(key, (Float) object);        } else if (object instanceof Long) {            editor.putLong(key, (Long) object);        } else {            editor.putString(key, object.toString());        }        SharedPreferencesCompat.apply(editor);    }    /**     * 得到保存数据的方法     */    public static Object get(Context context, String key, Object defaultObject) {        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);        if (defaultObject instanceof String) {            return sp.getString(key, (String) defaultObject);        } else if (defaultObject instanceof Integer) {            return sp.getInt(key, (Integer) defaultObject);        } else if (defaultObject instanceof Boolean) {            return sp.getBoolean(key, (Boolean) defaultObject);        } else if (defaultObject instanceof Float) {            return sp.getFloat(key, (Float) defaultObject);        } else if (defaultObject instanceof Long) {            return sp.getLong(key, (Long) defaultObject);        }        return null;    }    /**     * 移除某个key值对应的值     */    public static void remove(Context context, String key) {        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);        SharedPreferences.Editor editor = sp.edit();        editor.remove(key);        SharedPreferencesCompat.apply(editor);    }    /**     * 清楚所有数据     */    public static void clear(Context context) {        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);        SharedPreferences.Editor editor = sp.edit();        editor.clear();        SharedPreferencesCompat.apply(editor);    }    /**     * 查询某个key是否已经存在     */    public static boolean contains(Context context, String key) {        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);        return sp.contains(key);    }    /**     * 返回所有的键值对     */    public static Map<String, ?> getAll(Context context) {        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);        return sp.getAll();    }    /**     * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类     */    private static class SharedPreferencesCompat {        private static final Method sApplyMethod = findApplyMethod();        /**         * 反射查找apply的方法         */        private static Method findApplyMethod() {            try {                Class clz = SharedPreferences.Editor.class;                return clz.getMethod("apply");            } catch (NoSuchMethodException e) {                e.printStackTrace();            }            return null;        }        /**         * 如果找到则使用apply执行,否则使用commit         */        public static void apply(SharedPreferences.Editor editor) {            try {                if (sApplyMethod != null) {                    sApplyMethod.invoke(editor);                }            } catch (IllegalAccessException e) {                e.printStackTrace();            } catch (InvocationTargetException e) {                e.printStackTrace();            }            editor.commit();        }    }}

11、ListAdapter ViewHolder封装类 SimpleViewHolder.java

public class SimpleViewHolder{    @SuppressWarnings("unchecked")    public static <T extends View> T get(View view, int id)    {        SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();        if (viewHolder == null)        {            viewHolder = new SparseArray<View>();            view.setTag(viewHolder);        }        View childView = viewHolder.get(id);        if (childView == null)        {            childView = view.findViewById(id);            viewHolder.put(id, childView);        }        return (T) childView;    }}

12、字符串辅助工具类 StringUtils.java

public class StringUtils {    /**     * 判断是空字串     */    public static boolean isStrEmpty(String str) {        if (str == null)            return true;        str = str.trim();        if (str.length() <= 0)            return true;        if ("null".equalsIgnoreCase(str))            return true;        return false;    }    public static boolean isEmpty(CharSequence cs) {        return cs == null || cs.length() == 0;    }}

13、倒计时辅助工具类(应用场景:短信验证码倒计时)

public class TimeCountUtil extends CountDownTimer {    private Activity mActivity;    private Button btn; //按钮    public TimeCountUtil(long millisInFuture, long countDownInterval, Button btn, Activity mActivity) {        super(millisInFuture, countDownInterval);        this.btn = btn;        this.mActivity = mActivity;    }    /**     * @param millisInFuture    The number of millis in the future from the call     *                          to {@link #start()} until the countdown is done and {@link #onFinish()}     *                          is called.     * @param countDownInterval The interval along the way to receive     *                          {@link #onTick(long)} callbacks.     */    public TimeCountUtil(long millisInFuture, long countDownInterval) {        super(millisInFuture, countDownInterval);    }    @Override    public void onTick(long millisUntilFinished) {        btn.setClickable(false); //设置不能点击        if (0 < (millisUntilFinished / 1000) && (millisUntilFinished / 1000) < 100) {            btn.setText("0" + millisUntilFinished / 1000 + "秒后可重新发送"); //设置倒计时时间        } else {            btn.setText(millisUntilFinished / 1000 + "秒后可重新发送"); //设置倒计时时间        }        Spannable span = new SpannableString(btn.getText().toString());  //获取按钮的文字        span.setSpan(new ForegroundColorSpan(Color.YELLOW), 0, 3, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);  //倒计时时颜色为红色        btn.setText(span);    }    @Override    public void onFinish() {        btn.setText("重新获取");        btn.setClickable(true);    }    public static int ComparisonTime(String data1,String data2){        java.text.DateFormat df=new java.text.SimpleDateFormat("yyyy-MM-dd");        java.util.Calendar c1=java.util.Calendar.getInstance();        java.util.Calendar c2=java.util.Calendar.getInstance();        try        {            c1.setTime(df.parse(data1));            c2.setTime(df.parse(data2));        }catch(java.text.ParseException e){            System.err.println("格式不正确");        }        /**         * if(result==0)         * System.out.println("c1相等c2");         * else if(result<0)         * System.out.println("c1小于c2");         * else         *  System.out.println("c1大于c2");         */        return c1.compareTo(c2);    }    /**     * 格式化时间     * @param time     * @return     */    public static int formatDateTime(String time) {        SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm");        if(time==null ||"".equals(time)){            return -2;        }        Date date = null;        try {            date = format.parse(time);        } catch (ParseException e) {            e.printStackTrace();        }        Calendar current = Calendar.getInstance();        Calendar today = Calendar.getInstance();    //今天        today.set(Calendar.YEAR, current.get(Calendar.YEAR));        today.set(Calendar.MONTH, current.get(Calendar.MONTH));        today.set(Calendar.DAY_OF_MONTH,current.get(Calendar.DAY_OF_MONTH));        //  Calendar.HOUR——12小时制的小时数 Calendar.HOUR_OF_DAY——24小时制的小时数        today.set( Calendar.HOUR_OF_DAY, 0);        today.set( Calendar.MINUTE, 0);        today.set(Calendar.SECOND, 0);        Calendar yesterday = Calendar.getInstance();    //昨天        yesterday.set(Calendar.YEAR, current.get(Calendar.YEAR));        yesterday.set(Calendar.MONTH, current.get(Calendar.MONTH));        yesterday.set(Calendar.DAY_OF_MONTH,current.get(Calendar.DAY_OF_MONTH)-1);        yesterday.set( Calendar.HOUR_OF_DAY, 0);        yesterday.set( Calendar.MINUTE, 0);        yesterday.set(Calendar.SECOND, 0);        current.setTime(date);        if(current.after(today)){            return 0;        }else if(current.before(today) && current.after(yesterday)){            return -1;        }else{            return 1;        }    }    public static String getDateToString(long time) {        Date d = new Date(time);        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");        return sf.format(d);        }}

14、Toast辅助工具类 ToastUtils.java

public final class ToastUtils{    public static int CONSTANT_DURA = Toast.LENGTH_SHORT;    private static String LAST_MSG = "";    /**     * 当点击一个按钮会toast一条消息时,如果快速点击多次,会多次显示这条相同的信息。 现在加了一个判断,如果toast的内容相同,则取消之。     */    private static Handler TOAST_HANDLER = new Handler();    private static Runnable TOAST_RUNNABLE = new Runnable()    {        @Override        public void run()        {            LAST_MSG = "";        }    };    /**     * Find text from resourse and show into toast message     *     * @param activity     *            {@link Activity} used to create the {@link Toast} message     * @param messageResourceId     *            The resource containing the message to be displayed     */    public static void show(final Activity activity, final int messageResourceId)    {        ToastUtils.show(activity, messageResourceId, ToastUtils.CONSTANT_DURA);    }    /**     * Find text from resourse and show into toast message with custome time     * {@link Timer} in millisecond     *     * @param activity     *            {@link Activity} used to create the {@link Toast} message     * @param messageResourceId     *            The resource containing the message to be displayed     * @param duration     *            How long to display the message. Either     *            {@link Toast#LENGTH_SHORT} or {@link Toast#LENGTH_LONG}     */    public static void show(final Activity activity,                            final int messageResourceId, final int duration)    {        ToastUtils.showToast(activity, activity.getString(messageResourceId),                null, duration);    }    /**     * Toast directly pass string to file to an argument     *     * @param activity     *            {@link Activity} used to create the {@link Toast} message     * @param message     *            The message to be displayed     */    public static void show(final Activity activity, final String message)    {        ToastUtils.show(activity, message, ToastUtils.CONSTANT_DURA);    }    /**     * Toast directly pass string to file to an argument with custom     * {@link Toast} message     *     * @param activity     *            {@link Activity} used to create the {@link Toast} message     * @param message     *            The message to be displayed     * @param duration     *            How long to display the message. Either     *            {@link Toast#LENGTH_SHORT} or {@link Toast#LENGTH_LONG}     */    public static void show(final Activity activity, final String message,                            final int duration)    {        ToastUtils.showToast(activity, message, null, duration);    }    /**     * Make a standard toast that displays a {@link View}.     *     * @param activity     *            {@link Activity} used to create the {@link Toast} message     * @param view     *            The {@link View} to show     */    public static void show(final Activity activity, final View view)    {        ToastUtils.show(activity, view, ToastUtils.CONSTANT_DURA);    }    /**     * Make a standard toast that displays a {@link View}.     *     * @param activity     *            {@link Activity} used to create the {@link Toast} message     * @param view     *            The {@link View} to show     * @param duration     *            How long to display the message. Either     *            {@link Toast#LENGTH_SHORT} or {@link Toast#LENGTH_LONG}     */    public static void show(final Activity activity, final View view,                            final int duration)    {        ToastUtils.showToast(activity, null, view, duration);    }    /**     * @param activity     *            {@link Activity} used to create the {@link Toast} message.     * @param message     *            The message to be displayed.     * @param view     *            The {@link View} to be displayed.     * @param duration     *            How long to display the message. Either     *            {@link Toast#LENGTH_SHORT} or {@link Toast#LENGTH_LONG}.     */    private static void showToast(final Activity activity,                                  final String message, final View view, final int duration)    {        if (activity == null)        {            return;        }        if (TextUtils.isEmpty(message) && view == null)        {            return;        }        final Context context = activity.getApplicationContext();        /*         * XiaoMi的机器:         * java.lang.RuntimeException: Failed to register input channel.  Check logs for details.         * 只能猜测是Toast时出现的错误,try-catch试试         */        try        {            activity.runOnUiThread(new Runnable()            {                @Override                public void run()                {                    if (!StringUtils.isEmpty(message)                            && !message.equals(LAST_MSG))                    {                        final Toast toast = Toast.makeText(context, message,                                duration);                        LAST_MSG = message;                        if (view != null)                        {                            toast.setView(view);                        }                        toast.show();                        /*                         * http://blog.csdn.net/zapzqc/article/details/8502646                         * LONG : 3500ms, SHORT : 2000ms                         * Toast会判断,使得只能是这两个值                         */                        int delay = duration == Toast.LENGTH_LONG ? 3500 : 2000;                        TOAST_HANDLER.postDelayed(TOAST_RUNNABLE, delay);                    }                }            });        }        catch (Exception e)        {            e.printStackTrace();        }    }}
0 0
原创粉丝点击