Android快速开发系列 10个常用工具类

转载请标明出处:http://blog.youkuaiyun.com/lmj623565791/article/details/38965311,本文出自【张鸿洋的博客】

打开大家手上的项目,基本都会有一大批的辅助类,今天特此整理出10个基本每个项目中都会使用的工具类,用于快速开发~~

在此感谢群里给我发项目中工具类的兄弟/姐妹~

1、日志工具类L.java

  1. package com.zhy.utils; 
  2.  
  3. import android.util.Log; 
  4.  
  5. /**
  6. * Log统一管理类
  7. *
  8. *
  9. *
  10. */ 
  11. public class
  12.  
  13.     private L() 
  14.     { 
  15.         /* cannot be instantiated */ 
  16.         throw new UnsupportedOperationException("cannot be instantiated"); 
  17.     } 
  18.  
  19.     public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化 
  20.     private static final String TAG = "way"
  21.  
  22.     // 下面四个是默认tag的函数 
  23.     public static void i(String msg) 
  24.     { 
  25.         if (isDebug) 
  26.             Log.i(TAG, msg); 
  27.     } 
  28.  
  29.     public static void d(String msg) 
  30.     { 
  31.         if (isDebug) 
  32.             Log.d(TAG, msg); 
  33.     } 
  34.  
  35.     public static void e(String msg) 
  36.     { 
  37.         if (isDebug) 
  38.             Log.e(TAG, msg); 
  39.     } 
  40.  
  41.     public static void v(String msg) 
  42.     { 
  43.         if (isDebug) 
  44.             Log.v(TAG, msg); 
  45.     } 
  46.  
  47.     // 下面是传入自定义tag的函数 
  48.     public static void i(String tag, String msg) 
  49.     { 
  50.         if (isDebug) 
  51.             Log.i(tag, msg); 
  52.     } 
  53.  
  54.     public static void d(String tag, String msg) 
  55.     { 
  56.         if (isDebug) 
  57.             Log.i(tag, msg); 
  58.     } 
  59.  
  60.     public static void e(String tag, String msg) 
  61.     { 
  62.         if (isDebug) 
  63.             Log.i(tag, msg); 
  64.     } 
  65.  
  66.     public static void v(String tag, String msg) 
  67.     { 
  68.         if (isDebug) 
  69.             Log.i(tag, msg); 
  70.     } 
package com.zhy.utils;

import android.util.Log;

/**
 * Log统一管理类
 * 
 * 
 * 
 */
public class L
{

	private L()
	{
		/* cannot be instantiated */
		throw new UnsupportedOperationException("cannot be instantiated");
	}

	public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化
	private static final String TAG = "way";

	// 下面四个是默认tag的函数
	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 e(String msg)
	{
		if (isDebug)
			Log.e(TAG, msg);
	}

	public static void v(String msg)
	{
		if (isDebug)
			Log.v(TAG, msg);
	}

	// 下面是传入自定义tag的函数
	public static void i(String tag, String msg)
	{
		if (isDebug)
			Log.i(tag, msg);
	}

	public static void d(String tag, String msg)
	{
		if (isDebug)
			Log.i(tag, msg);
	}

	public static void e(String tag, String msg)
	{
		if (isDebug)
			Log.i(tag, msg);
	}

	public static void v(String tag, String msg)
	{
		if (isDebug)
			Log.i(tag, msg);
	}
}


网上看到的类,注释上应该原创作者的名字,很简单的一个类;网上也有很多提供把日志记录到SDCard上的,不过我是从来没记录过,所以引入个最简单的,大家可以进行评价是否需要扩充~~

2、Toast统一管理类

  1. package com.zhy.utils; 
  2.  
  3. import android.content.Context; 
  4. import android.widget.Toast; 
  5.  
  6. /**
  7. * Toast统一管理类
  8. *
  9. */ 
  10. public class
  11.  
  12.     private T() 
  13.     { 
  14.         /* cannot be instantiated */ 
  15.         throw new UnsupportedOperationException("cannot be instantiated"); 
  16.     } 
  17.  
  18.     public static boolean isShow = true
  19.  
  20.     /**
  21.      * 短时间显示Toast
  22.      *
  23.      * @param context
  24.      * @param message
  25.      */ 
  26.     public static void showShort(Context context, CharSequence message) 
  27.     { 
  28.         if (isShow) 
  29.             Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); 
  30.     } 
  31.  
  32.     /**
  33.      * 短时间显示Toast
  34.      *
  35.      * @param context
  36.      * @param message
  37.      */ 
  38.     public static void showShort(Context context, int message) 
  39.     { 
  40.         if (isShow) 
  41.             Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); 
  42.     } 
  43.  
  44.     /**
  45.      * 长时间显示Toast
  46.      *
  47.      * @param context
  48.      * @param message
  49.      */ 
  50.     public static void showLong(Context context, CharSequence message) 
  51.     { 
  52.         if (isShow) 
  53.             Toast.makeText(context, message, Toast.LENGTH_LONG).show(); 
  54.     } 
  55.  
  56.     /**
  57.      * 长时间显示Toast
  58.      *
  59.      * @param context
  60.      * @param message
  61.      */ 
  62.     public static void showLong(Context context, int message) 
  63.     { 
  64.         if (isShow) 
  65.             Toast.makeText(context, message, Toast.LENGTH_LONG).show(); 
  66.     } 
  67.  
  68.     /**
  69.      * 自定义显示Toast时间
  70.      *
  71.      * @param context
  72.      * @param message
  73.      * @param duration
  74.      */ 
  75.     public static void show(Context context, CharSequence message, int duration) 
  76.     { 
  77.         if (isShow) 
  78.             Toast.makeText(context, message, duration).show(); 
  79.     } 
  80.  
  81.     /**
  82.      * 自定义显示Toast时间
  83.      *
  84.      * @param context
  85.      * @param message
  86.      * @param duration
  87.      */ 
  88.     public static void show(Context context, int message, int duration) 
  89.     { 
  90.         if (isShow) 
  91.             Toast.makeText(context, message, duration).show(); 
  92.     } 
  93.  
package com.zhy.utils;

import android.content.Context;
import android.widget.Toast;

/**
 * Toast统一管理类
 * 
 */
public class T
{

	private T()
	{
		/* cannot be instantiated */
		throw new UnsupportedOperationException("cannot be instantiated");
	}

	public static boolean isShow = true;

	/**
	 * 短时间显示Toast
	 * 
	 * @param context
	 * @param message
	 */
	public static void showShort(Context context, CharSequence message)
	{
		if (isShow)
			Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 短时间显示Toast
	 * 
	 * @param context
	 * @param message
	 */
	public static void showShort(Context context, int message)
	{
		if (isShow)
			Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 长时间显示Toast
	 * 
	 * @param context
	 * @param message
	 */
	public static void showLong(Context context, CharSequence message)
	{
		if (isShow)
			Toast.makeText(context, message, Toast.LENGTH_LONG).show();
	}

	/**
	 * 长时间显示Toast
	 * 
	 * @param context
	 * @param message
	 */
	public static void showLong(Context context, int message)
	{
		if (isShow)
			Toast.makeText(context, message, Toast.LENGTH_LONG).show();
	}

	/**
	 * 自定义显示Toast时间
	 * 
	 * @param context
	 * @param message
	 * @param duration
	 */
	public static void show(Context context, CharSequence message, int duration)
	{
		if (isShow)
			Toast.makeText(context, message, duration).show();
	}

	/**
	 * 自定义显示Toast时间
	 * 
	 * @param context
	 * @param message
	 * @param duration
	 */
	public static void show(Context context, int message, int duration)
	{
		if (isShow)
			Toast.makeText(context, message, duration).show();
	}

}


也是非常简单的一个封装,能省则省了~~

3、SharedPreferences封装类SPUtils

  1. package com.zhy.utils; 
  2.  
  3. import java.lang.reflect.InvocationTargetException; 
  4. import java.lang.reflect.Method; 
  5. import java.util.Map; 
  6.  
  7. import android.content.Context; 
  8. import android.content.SharedPreferences; 
  9.  
  10. public class SPUtils 
  11.     /**
  12.      * 保存在手机里面的文件名
  13.      */ 
  14.     public static final String FILE_NAME = "share_data"
  15.  
  16.     /**
  17.      * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
  18.      *
  19.      * @param context
  20.      * @param key
  21.      * @param object
  22.      */ 
  23.     public static void put(Context context, String key, Object object) 
  24.     { 
  25.  
  26.         SharedPreferences sp = context.getSharedPreferences(FILE_NAME, 
  27.                 Context.MODE_PRIVATE); 
  28.         SharedPreferences.Editor editor = sp.edit(); 
  29.  
  30.         if (object instanceof String) 
  31.         { 
  32.             editor.putString(key, (String) object); 
  33.         } else if (object instanceof Integer) 
  34.         { 
  35.             editor.putInt(key, (Integer) object); 
  36.         } else if (object instanceof Boolean) 
  37.         { 
  38.             editor.putBoolean(key, (Boolean) object); 
  39.         } else if (object instanceof Float) 
  40.         { 
  41.             editor.putFloat(key, (Float) object); 
  42.         } else if (object instanceof Long) 
  43.         { 
  44.             editor.putLong(key, (Long) object); 
  45.         } else 
  46.         { 
  47.             editor.putString(key, object.toString()); 
  48.         } 
  49.  
  50.         SharedPreferencesCompat.apply(editor); 
  51.     } 
  52.  
  53.     /**
  54.      * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
  55.      *
  56.      * @param context
  57.      * @param key
  58.      * @param defaultObject
  59.      * @return
  60.      */ 
  61.     public static Object get(Context context, String key, Object defaultObject) 
  62.     { 
  63.         SharedPreferences sp = context.getSharedPreferences(FILE_NAME, 
  64.                 Context.MODE_PRIVATE); 
  65.  
  66.         if (defaultObject instanceof String) 
  67.         { 
  68.             return sp.getString(key, (String) defaultObject); 
  69.         } else if (defaultObject instanceof Integer) 
  70.         { 
  71.             return sp.getInt(key, (Integer) defaultObject); 
  72.         } else if (defaultObject instanceof Boolean) 
  73.         { 
  74.             return sp.getBoolean(key, (Boolean) defaultObject); 
  75.         } else if (defaultObject instanceof Float) 
  76.         { 
  77.             return sp.getFloat(key, (Float) defaultObject); 
  78.         } else if (defaultObject instanceof Long) 
  79.         { 
  80.             return sp.getLong(key, (Long) defaultObject); 
  81.         } 
  82.  
  83.         return null
  84.     } 
  85.  
  86.     /**
  87.      * 移除某个key值已经对应的值
  88.      * @param context
  89.      * @param key
  90.      */ 
  91.     public static void remove(Context context, String key) 
  92.     { 
  93.         SharedPreferences sp = context.getSharedPreferences(FILE_NAME, 
  94.                 Context.MODE_PRIVATE); 
  95.         SharedPreferences.Editor editor = sp.edit(); 
  96.         editor.remove(key); 
  97.         SharedPreferencesCompat.apply(editor); 
  98.     } 
  99.  
  100.     /**
  101.      * 清除所有数据
  102.      * @param context
  103.      */ 
  104.     public static void clear(Context context) 
  105.     { 
  106.         SharedPreferences sp = context.getSharedPreferences(FILE_NAME, 
  107.                 Context.MODE_PRIVATE); 
  108.         SharedPreferences.Editor editor = sp.edit(); 
  109.         editor.clear(); 
  110.         SharedPreferencesCompat.apply(editor); 
  111.     } 
  112.  
  113.     /**
  114.      * 查询某个key是否已经存在
  115.      * @param context
  116.      * @param key
  117.      * @return
  118.      */ 
  119.     public static boolean contains(Context context, String key) 
  120.     { 
  121.         SharedPreferences sp = context.getSharedPreferences(FILE_NAME, 
  122.                 Context.MODE_PRIVATE); 
  123.         return sp.contains(key); 
  124.     } 
  125.  
  126.     /**
  127.      * 返回所有的键值对
  128.      *
  129.      * @param context
  130.      * @return
  131.      */ 
  132.     public static Map<String, ?> getAll(Context context) 
  133.     { 
  134.         SharedPreferences sp = context.getSharedPreferences(FILE_NAME, 
  135.                 Context.MODE_PRIVATE); 
  136.         return sp.getAll(); 
  137.     } 
  138.  
  139.     /**
  140.      * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
  141.      *
  142.      * @author zhy
  143.      *
  144.      */ 
  145.     private static class SharedPreferencesCompat 
  146.     { 
  147.         private static final Method sApplyMethod = findApplyMethod(); 
  148.  
  149.         /**
  150.          * 反射查找apply的方法
  151.          *
  152.          * @return
  153.          */ 
  154.         @SuppressWarnings({ "unchecked", "rawtypes" }) 
  155.         private static Method findApplyMethod() 
  156.         { 
  157.             try 
  158.             { 
  159.                 Class clz = SharedPreferences.Editor.class
  160.                 return clz.getMethod("apply"); 
  161.             } catch (NoSuchMethodException e) 
  162.             { 
  163.             } 
  164.  
  165.             return null
  166.         } 
  167.  
  168.         /**
  169.          * 如果找到则使用apply执行,否则使用commit
  170.          *
  171.          * @param editor
  172.          */ 
  173.         public static void apply(SharedPreferences.Editor editor) 
  174.         { 
  175.             try 
  176.             { 
  177.                 if (sApplyMethod != null
  178.                 { 
  179.                     sApplyMethod.invoke(editor); 
  180.                     return
  181.                 } 
  182.             } catch (IllegalArgumentException e) 
  183.             { 
  184.             } catch (IllegalAccessException e) 
  185.             { 
  186.             } catch (InvocationTargetException e) 
  187.             { 
  188.             } 
  189.             editor.commit(); 
  190.         } 
  191.     } 
  192.  
package com.zhy.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

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

public class SPUtils
{
	/**
	 * 保存在手机里面的文件名
	 */
	public static final String FILE_NAME = "share_data";

	/**
	 * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
	 * 
	 * @param context
	 * @param key
	 * @param object
	 */
	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);
	}

	/**
	 * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
	 * 
	 * @param context
	 * @param key
	 * @param defaultObject
	 * @return
	 */
	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值已经对应的值
	 * @param context
	 * @param 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);
	}

	/**
	 * 清除所有数据
	 * @param context
	 */
	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是否已经存在
	 * @param context
	 * @param key
	 * @return
	 */
	public static boolean contains(Context context, String key)
	{
		SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
				Context.MODE_PRIVATE);
		return sp.contains(key);
	}

	/**
	 * 返回所有的键值对
	 * 
	 * @param context
	 * @return
	 */
	public static Map<String, ?> getAll(Context context)
	{
		SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
				Context.MODE_PRIVATE);
		return sp.getAll();
	}

	/**
	 * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
	 * 
	 * @author zhy
	 * 
	 */
	private static class SharedPreferencesCompat
	{
		private static final Method sApplyMethod = findApplyMethod();

		/**
		 * 反射查找apply的方法
		 * 
		 * @return
		 */
		@SuppressWarnings({ "unchecked", "rawtypes" })
		private static Method findApplyMethod()
		{
			try
			{
				Class clz = SharedPreferences.Editor.class;
				return clz.getMethod("apply");
			} catch (NoSuchMethodException e)
			{
			}

			return null;
		}

		/**
		 * 如果找到则使用apply执行,否则使用commit
		 * 
		 * @param editor
		 */
		public static void apply(SharedPreferences.Editor editor)
		{
			try
			{
				if (sApplyMethod != null)
				{
					sApplyMethod.invoke(editor);
					return;
				}
			} catch (IllegalArgumentException e)
			{
			} catch (IllegalAccessException e)
			{
			} catch (InvocationTargetException e)
			{
			}
			editor.commit();
		}
	}

}

对SharedPreference的使用做了建议的封装,对外公布出put,get,remove,clear等等方法;

注意一点,里面所有的commit操作使用了SharedPreferencesCompat.apply进行了替代,目的是尽可能的使用apply代替commit

首先说下为什么,因为commit方法是同步的,并且我们很多时候的commit操作都是UI线程中,毕竟是IO操作,尽可能异步;

所以我们使用apply进行替代,apply异步的进行写入;

但是apply相当于commit来说是new API呢,为了更好的兼容,我们做了适配;

SharedPreferencesCompat也可以给大家创建兼容类提供了一定的参考~~


4、单位转换类 DensityUtils

  1. package com.zhy.utils; 
  2.  
  3. import android.content.Context; 
  4. import android.util.TypedValue; 
  5.  
  6. /**
  7. * 常用单位转换的辅助类
  8. *
  9. *
  10. *
  11. */ 
  12. public class DensityUtils 
  13.     private DensityUtils() 
  14.     { 
  15.         /* cannot be instantiated */ 
  16.         throw new UnsupportedOperationException("cannot be instantiated"); 
  17.     } 
  18.  
  19.     /**
  20.      * dp转px
  21.      *
  22.      * @param context
  23.      * @param val
  24.      * @return
  25.      */ 
  26.     public static int dp2px(Context context, float dpVal) 
  27.     { 
  28.         return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 
  29.                 dpVal, context.getResources().getDisplayMetrics()); 
  30.     } 
  31.  
  32.     /**
  33.      * sp转px
  34.      *
  35.      * @param context
  36.      * @param val
  37.      * @return
  38.      */ 
  39.     public static int sp2px(Context context, float spVal) 
  40.     { 
  41.         return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 
  42.                 spVal, context.getResources().getDisplayMetrics()); 
  43.     } 
  44.  
  45.     /**
  46.      * px转dp
  47.      *
  48.      * @param context
  49.      * @param pxVal
  50.      * @return
  51.      */ 
  52.     public static float px2dp(Context context, float pxVal) 
  53.     { 
  54.         final float scale = context.getResources().getDisplayMetrics().density; 
  55.         return (pxVal / scale); 
  56.     } 
  57.  
  58.     /**
  59.      * px转sp
  60.      *
  61.      * @param fontScale
  62.      * @param pxVal
  63.      * @return
  64.      */ 
  65.     public static float px2sp(Context context, float pxVal) 
  66.     { 
  67.         return (pxVal / context.getResources().getDisplayMetrics().scaledDensity); 
  68.     } 
  69.  
package com.zhy.utils;

import android.content.Context;
import android.util.TypedValue;

/**
 * 常用单位转换的辅助类
 * 
 * 
 * 
 */
public class DensityUtils
{
	private DensityUtils()
	{
		/* cannot be instantiated */
		throw new UnsupportedOperationException("cannot be instantiated");
	}

	/**
	 * dp转px
	 * 
	 * @param context
	 * @param val
	 * @return
	 */
	public static int dp2px(Context context, float dpVal)
	{
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
				dpVal, context.getResources().getDisplayMetrics());
	}

	/**
	 * sp转px
	 * 
	 * @param context
	 * @param val
	 * @return
	 */
	public static int sp2px(Context context, float spVal)
	{
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
				spVal, context.getResources().getDisplayMetrics());
	}

	/**
	 * px转dp
	 * 
	 * @param context
	 * @param pxVal
	 * @return
	 */
	public static float px2dp(Context context, float pxVal)
	{
		final float scale = context.getResources().getDisplayMetrics().density;
		return (pxVal / scale);
	}

	/**
	 * px转sp
	 * 
	 * @param fontScale
	 * @param pxVal
	 * @return
	 */
	public static float px2sp(Context context, float pxVal)
	{
		return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
	}

}

5、SD卡相关辅助类 SDCardUtils

  1. package com.zhy.utils; 
  2.  
  3. import java.io.File; 
  4.  
  5. import android.os.Environment; 
  6. import android.os.StatFs; 
  7.  
  8. /**
  9. * SD卡相关的辅助类
  10. *
  11. *
  12. *
  13. */ 
  14. public class SDCardUtils 
  15.     private SDCardUtils() 
  16.     { 
  17.         /* cannot be instantiated */ 
  18.         throw new UnsupportedOperationException("cannot be instantiated"); 
  19.     } 
  20.  
  21.     /**
  22.      * 判断SDCard是否可用
  23.      *
  24.      * @return
  25.      */ 
  26.     public static boolean isSDCardEnable() 
  27.     { 
  28.         return Environment.getExternalStorageState().equals( 
  29.                 Environment.MEDIA_MOUNTED); 
  30.  
  31.     } 
  32.  
  33.     /**
  34.      * 获取SD卡路径
  35.      *
  36.      * @return
  37.      */ 
  38.     public static String getSDCardPath() 
  39.     { 
  40.         return Environment.getExternalStorageDirectory().getAbsolutePath() 
  41.                 + File.separator; 
  42.     } 
  43.  
  44.     /**
  45.      * 获取SD卡的剩余容量 单位byte
  46.      *
  47.      * @return
  48.      */ 
  49.     public static long getSDCardAllSize() 
  50.     { 
  51.         if (isSDCardEnable()) 
  52.         { 
  53.             StatFs stat = new StatFs(getSDCardPath()); 
  54.             // 获取空闲的数据块的数量 
  55.             long availableBlocks = (long) stat.getAvailableBlocks() - 4
  56.             // 获取单个数据块的大小(byte) 
  57.             long freeBlocks = stat.getAvailableBlocks(); 
  58.             return freeBlocks * availableBlocks; 
  59.         } 
  60.         return 0
  61.     } 
  62.  
  63.     /**
  64.      * 获取指定路径所在空间的剩余可用容量字节数,单位byte
  65.      *
  66.      * @param filePath
  67.      * @return 容量字节 SDCard可用空间,内部存储可用空间
  68.      */ 
  69.     public static long getFreeBytes(String filePath) 
  70.     { 
  71.         // 如果是sd卡的下的路径,则获取sd卡可用容量 
  72.         if (filePath.startsWith(getSDCardPath())) 
  73.         { 
  74.             filePath = getSDCardPath(); 
  75.         } else 
  76.         {// 如果是内部存储的路径,则获取内存存储的可用容量 
  77.             filePath = Environment.getDataDirectory().getAbsolutePath(); 
  78.         } 
  79.         StatFs stat = new StatFs(filePath); 
  80.         long availableBlocks = (long) stat.getAvailableBlocks() - 4
  81.         return stat.getBlockSize() * availableBlocks; 
  82.     } 
  83.  
  84.     /**
  85.      * 获取系统存储路径
  86.      *
  87.      * @return
  88.      */ 
  89.     public static String getRootDirectoryPath() 
  90.     { 
  91.         return Environment.getRootDirectory().getAbsolutePath(); 
  92.     } 
  93.  
  94.  
package com.zhy.utils;

import java.io.File;

import android.os.Environment;
import android.os.StatFs;

/**
 * SD卡相关的辅助类
 * 
 * 
 * 
 */
public class SDCardUtils
{
	private SDCardUtils()
	{
		/* cannot be instantiated */
		throw new UnsupportedOperationException("cannot be instantiated");
	}

	/**
	 * 判断SDCard是否可用
	 * 
	 * @return
	 */
	public static boolean isSDCardEnable()
	{
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);

	}

	/**
	 * 获取SD卡路径
	 * 
	 * @return
	 */
	public static String getSDCardPath()
	{
		return Environment.getExternalStorageDirectory().getAbsolutePath()
				+ File.separator;
	}

	/**
	 * 获取SD卡的剩余容量 单位byte
	 * 
	 * @return
	 */
	public static long getSDCardAllSize()
	{
		if (isSDCardEnable())
		{
			StatFs stat = new StatFs(getSDCardPath());
			// 获取空闲的数据块的数量
			long availableBlocks = (long) stat.getAvailableBlocks() - 4;
			// 获取单个数据块的大小(byte)
			long freeBlocks = stat.getAvailableBlocks();
			return freeBlocks * availableBlocks;
		}
		return 0;
	}

	/**
	 * 获取指定路径所在空间的剩余可用容量字节数,单位byte
	 * 
	 * @param filePath
	 * @return 容量字节 SDCard可用空间,内部存储可用空间
	 */
	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;
	}

	/**
	 * 获取系统存储路径
	 * 
	 * @return
	 */
	public static String getRootDirectoryPath()
	{
		return Environment.getRootDirectory().getAbsolutePath();
	}


}

6、屏幕相关辅助类 ScreenUtils

  1. package com.zhy.utils; 
  2.  
  3. import android.app.Activity; 
  4. import android.content.Context; 
  5. import android.graphics.Bitmap; 
  6. import android.graphics.Rect; 
  7. import android.util.DisplayMetrics; 
  8. import android.view.View; 
  9. import android.view.WindowManager; 
  10.  
  11. /**
  12. * 获得屏幕相关的辅助类
  13. *
  14. *
  15. *
  16. */ 
  17. public class ScreenUtils 
  18.     private ScreenUtils() 
  19.     { 
  20.         /* cannot be instantiated */ 
  21.         throw new UnsupportedOperationException("cannot be instantiated"); 
  22.     } 
  23.  
  24.     /**
  25.      * 获得屏幕高度
  26.      *
  27.      * @param context
  28.      * @return
  29.      */ 
  30.     public static int getScreenWidth(Context context) 
  31.     { 
  32.         WindowManager wm = (WindowManager) context 
  33.                 .getSystemService(Context.WINDOW_SERVICE); 
  34.         DisplayMetrics outMetrics = new DisplayMetrics(); 
  35.         wm.getDefaultDisplay().getMetrics(outMetrics); 
  36.         return outMetrics.widthPixels; 
  37.     } 
  38.  
  39.     /**
  40.      * 获得屏幕宽度
  41.      *
  42.      * @param context
  43.      * @return
  44.      */ 
  45.     public static int getScreenHeight(Context context) 
  46.     { 
  47.         WindowManager wm = (WindowManager) context 
  48.                 .getSystemService(Context.WINDOW_SERVICE); 
  49.         DisplayMetrics outMetrics = new DisplayMetrics(); 
  50.         wm.getDefaultDisplay().getMetrics(outMetrics); 
  51.         return outMetrics.heightPixels; 
  52.     } 
  53.  
  54.     /**
  55.      * 获得状态栏的高度
  56.      *
  57.      * @param context
  58.      * @return
  59.      */ 
  60.     public static int getStatusHeight(Context context) 
  61.     { 
  62.  
  63.         int statusHeight = -1
  64.         try 
  65.         { 
  66.             Class<?> clazz = Class.forName("com.android.internal.R$dimen"); 
  67.             Object object = clazz.newInstance(); 
  68.             int height = Integer.parseInt(clazz.getField("status_bar_height"
  69.                     .get(object).toString()); 
  70.             statusHeight = context.getResources().getDimensionPixelSize(height); 
  71.         } catch (Exception e) 
  72.         { 
  73.             e.printStackTrace(); 
  74.         } 
  75.         return statusHeight; 
  76.     } 
  77.  
  78.     /**
  79.      * 获取当前屏幕截图,包含状态栏
  80.      *
  81.      * @param activity
  82.      * @return
  83.      */ 
  84.     public static Bitmap snapShotWithStatusBar(Activity activity) 
  85.     { 
  86.         View view = activity.getWindow().getDecorView(); 
  87.         view.setDrawingCacheEnabled(true); 
  88.         view.buildDrawingCache(); 
  89.         Bitmap bmp = view.getDrawingCache(); 
  90.         int width = getScreenWidth(activity); 
  91.         int height = getScreenHeight(activity); 
  92.         Bitmap bp = null
  93.         bp = Bitmap.createBitmap(bmp, 0, 0, width, height); 
  94.         view.destroyDrawingCache(); 
  95.         return bp; 
  96.  
  97.     } 
  98.  
  99.     /**
  100.      * 获取当前屏幕截图,不包含状态栏
  101.      *
  102.      * @param activity
  103.      * @return
  104.      */ 
  105.     public static Bitmap snapShotWithoutStatusBar(Activity activity) 
  106.     { 
  107.         View view = activity.getWindow().getDecorView(); 
  108.         view.setDrawingCacheEnabled(true); 
  109.         view.buildDrawingCache(); 
  110.         Bitmap bmp = view.getDrawingCache(); 
  111.         Rect frame = new Rect(); 
  112.         activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); 
  113.         int statusBarHeight = frame.top; 
  114.  
  115.         int width = getScreenWidth(activity); 
  116.         int height = getScreenHeight(activity); 
  117.         Bitmap bp = null
  118.         bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height 
  119.                 - statusBarHeight); 
  120.         view.destroyDrawingCache(); 
  121.         return bp; 
  122.  
  123.     } 
  124.  
package com.zhy.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;

/**
 * 获得屏幕相关的辅助类
 * 
 * 
 * 
 */
public class ScreenUtils
{
	private ScreenUtils()
	{
		/* cannot be instantiated */
		throw new UnsupportedOperationException("cannot be instantiated");
	}

	/**
	 * 获得屏幕高度
	 * 
	 * @param context
	 * @return
	 */
	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;
	}

	/**
	 * 获得屏幕宽度
	 * 
	 * @param context
	 * @return
	 */
	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;
	}

	/**
	 * 获得状态栏的高度
	 * 
	 * @param context
	 * @return
	 */
	public static int getStatusHeight(Context context)
	{

		int statusHeight = -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());
			statusHeight = context.getResources().getDimensionPixelSize(height);
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return statusHeight;
	}

	/**
	 * 获取当前屏幕截图,包含状态栏
	 * 
	 * @param activity
	 * @return
	 */
	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;

	}

	/**
	 * 获取当前屏幕截图,不包含状态栏
	 * 
	 * @param activity
	 * @return
	 */
	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;

	}

}

7、App相关辅助类

  1. package com.zhy.utils; 
  2.  
  3. import android.content.Context; 
  4. import android.content.pm.PackageInfo; 
  5. import android.content.pm.PackageManager; 
  6. import android.content.pm.PackageManager.NameNotFoundException; 
  7.  
  8. /**
  9. * 跟App相关的辅助类
  10. *
  11. *
  12. *
  13. */ 
  14. public class AppUtils 
  15.  
  16.     private AppUtils() 
  17.     { 
  18.         /* cannot be instantiated */ 
  19.         throw new UnsupportedOperationException("cannot be instantiated"); 
  20.  
  21.     } 
  22.  
  23.     /**
  24.      * 获取应用程序名称
  25.      */ 
  26.     public static String getAppName(Context context) 
  27.     { 
  28.         try 
  29.         { 
  30.             PackageManager packageManager = context.getPackageManager(); 
  31.             PackageInfo packageInfo = packageManager.getPackageInfo( 
  32.                     context.getPackageName(), 0); 
  33.             int labelRes = packageInfo.applicationInfo.labelRes; 
  34.             return context.getResources().getString(labelRes); 
  35.         } catch (NameNotFoundException e) 
  36.         { 
  37.             e.printStackTrace(); 
  38.         } 
  39.         return null
  40.     } 
  41.  
  42.     /**
  43.      * [获取应用程序版本名称信息]
  44.      *
  45.      * @param context
  46.      * @return 当前应用的版本名称
  47.      */ 
  48.     public static String getVersionName(Context context) 
  49.     { 
  50.         try 
  51.         { 
  52.             PackageManager packageManager = context.getPackageManager(); 
  53.             PackageInfo packageInfo = packageManager.getPackageInfo( 
  54.                     context.getPackageName(), 0); 
  55.             return packageInfo.versionName; 
  56.  
  57.         } catch (NameNotFoundException e) 
  58.         { 
  59.             e.printStackTrace(); 
  60.         } 
  61.         return null
  62.     } 
  63.  
package com.zhy.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;

/**
 * 跟App相关的辅助类
 * 
 * 
 * 
 */
public class AppUtils
{

	private AppUtils()
	{
		/* cannot be instantiated */
		throw new UnsupportedOperationException("cannot 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 (NameNotFoundException e)
		{
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * [获取应用程序版本名称信息]
	 * 
	 * @param context
	 * @return 当前应用的版本名称
	 */
	public static String getVersionName(Context context)
	{
		try
		{
			PackageManager packageManager = context.getPackageManager();
			PackageInfo packageInfo = packageManager.getPackageInfo(
					context.getPackageName(), 0);
			return packageInfo.versionName;

		} catch (NameNotFoundException e)
		{
			e.printStackTrace();
		}
		return null;
	}

}

8、软键盘相关辅助类KeyBoardUtils

  1. package com.zhy.utils; 
  2.  
  3. import android.content.Context; 
  4. import android.view.inputmethod.InputMethodManager; 
  5. import android.widget.EditText; 
  6.  
  7. /**
  8. * 打开或关闭软键盘
  9. *
  10. * @author zhy
  11. *
  12. */ 
  13. public class KeyBoardUtils 
  14.     /**
  15.      * 打卡软键盘
  16.      *
  17.      * @param mEditText
  18.      *            输入框
  19.      * @param mContext
  20.      *            上下文
  21.      */ 
  22.     public static void openKeybord(EditText mEditText, Context mContext) 
  23.     { 
  24.         InputMethodManager imm = (InputMethodManager) mContext 
  25.                 .getSystemService(Context.INPUT_METHOD_SERVICE); 
  26.         imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN); 
  27.         imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 
  28.                 InputMethodManager.HIDE_IMPLICIT_ONLY); 
  29.     } 
  30.  
  31.     /**
  32.      * 关闭软键盘
  33.      *
  34.      * @param mEditText
  35.      *            输入框
  36.      * @param mContext
  37.      *            上下文
  38.      */ 
  39.     public static void closeKeybord(EditText mEditText, Context mContext) 
  40.     { 
  41.         InputMethodManager imm = (InputMethodManager) mContext 
  42.                 .getSystemService(Context.INPUT_METHOD_SERVICE); 
  43.  
  44.         imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0); 
  45.     } 
package com.zhy.utils;

import android.content.Context;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

/**
 * 打开或关闭软键盘
 * 
 * @author zhy
 * 
 */
public class KeyBoardUtils
{
	/**
	 * 打卡软键盘
	 * 
	 * @param mEditText
	 *            输入框
	 * @param mContext
	 *            上下文
	 */
	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);
	}

	/**
	 * 关闭软键盘
	 * 
	 * @param mEditText
	 *            输入框
	 * @param mContext
	 *            上下文
	 */
	public static void closeKeybord(EditText mEditText, Context mContext)
	{
		InputMethodManager imm = (InputMethodManager) mContext
				.getSystemService(Context.INPUT_METHOD_SERVICE);

		imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
	}
}

9、网络相关辅助类 NetUtils

  1. package com.zhy.utils; 
  2.  
  3. import android.app.Activity; 
  4. import android.content.ComponentName; 
  5. import android.content.Context; 
  6. import android.content.Intent; 
  7. import android.net.ConnectivityManager; 
  8. import android.net.NetworkInfo; 
  9.  
  10. /**
  11. * 跟网络相关的工具类
  12. *
  13. *
  14. *
  15. */ 
  16. public class NetUtils 
  17.     private NetUtils() 
  18.     { 
  19.         /* cannot be instantiated */ 
  20.         throw new UnsupportedOperationException("cannot be instantiated"); 
  21.     } 
  22.  
  23.     /**
  24.      * 判断网络是否连接
  25.      *
  26.      * @param context
  27.      * @return
  28.      */ 
  29.     public static boolean isConnected(Context context) 
  30.     { 
  31.  
  32.         ConnectivityManager connectivity = (ConnectivityManager) context 
  33.                 .getSystemService(Context.CONNECTIVITY_SERVICE); 
  34.  
  35.         if (null != connectivity) 
  36.         { 
  37.  
  38.             NetworkInfo info = connectivity.getActiveNetworkInfo(); 
  39.             if (null != info && info.isConnected()) 
  40.             { 
  41.                 if (info.getState() == NetworkInfo.State.CONNECTED) 
  42.                 { 
  43.                     return true
  44.                 } 
  45.             } 
  46.         } 
  47.         return false
  48.     } 
  49.  
  50.     /**
  51.      * 判断是否是wifi连接
  52.      */ 
  53.     public static boolean isWifi(Context context) 
  54.     { 
  55.         ConnectivityManager cm = (ConnectivityManager) context 
  56.                 .getSystemService(Context.CONNECTIVITY_SERVICE); 
  57.  
  58.         if (cm == null
  59.             return false
  60.         return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI; 
  61.  
  62.     } 
  63.  
  64.     /**
  65.      * 打开网络设置界面
  66.      */ 
  67.     public static void openSetting(Activity activity) 
  68.     { 
  69.         Intent intent = new Intent("/"); 
  70.         ComponentName cm = new ComponentName("com.android.settings"
  71.                 "com.android.settings.WirelessSettings"); 
  72.         intent.setComponent(cm); 
  73.         intent.setAction("android.intent.action.VIEW"); 
  74.         activity.startActivityForResult(intent, 0); 
  75.     } 
  76.  
package com.zhy.utils;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * 跟网络相关的工具类
 * 
 * 
 * 
 */
public class NetUtils
{
	private NetUtils()
	{
		/* cannot be instantiated */
		throw new UnsupportedOperationException("cannot be instantiated");
	}

	/**
	 * 判断网络是否连接
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isConnected(Context context)
	{

		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		if (null != connectivity)
		{

			NetworkInfo info = connectivity.getActiveNetworkInfo();
			if (null != info && info.isConnected())
			{
				if (info.getState() == NetworkInfo.State.CONNECTED)
				{
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 判断是否是wifi连接
	 */
	public static boolean isWifi(Context context)
	{
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		if (cm == null)
			return false;
		return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;

	}

	/**
	 * 打开网络设置界面
	 */
	public static void openSetting(Activity activity)
	{
		Intent intent = new Intent("/");
		ComponentName cm = new ComponentName("com.android.settings",
				"com.android.settings.WirelessSettings");
		intent.setComponent(cm);
		intent.setAction("android.intent.action.VIEW");
		activity.startActivityForResult(intent, 0);
	}

}


10、Http相关辅助类 HttpUtils

  1. package com.zhy.utils; 
  2.  
  3. import java.io.BufferedReader; 
  4. import java.io.ByteArrayOutputStream; 
  5. import java.io.IOException; 
  6. import java.io.InputStream; 
  7. import java.io.InputStreamReader; 
  8. import java.io.PrintWriter; 
  9. import java.net.HttpURLConnection; 
  10. import java.net.URL; 
  11.  
  12. /**
  13. * Http请求的工具类
  14. *
  15. * @author zhy
  16. *
  17. */ 
  18. public class HttpUtils 
  19.  
  20.     private static final int TIMEOUT_IN_MILLIONS = 5000
  21.  
  22.     public interface CallBack 
  23.     { 
  24.         void onRequestComplete(String result); 
  25.     } 
  26.  
  27.  
  28.     /**
  29.      * 异步的Get请求
  30.      *
  31.      * @param urlStr
  32.      * @param callBack
  33.      */ 
  34.     public static void doGetAsyn(final String urlStr, final CallBack callBack) 
  35.     { 
  36.         new Thread() 
  37.         { 
  38.             public void run() 
  39.             { 
  40.                 try 
  41.                 { 
  42.                     String result = doGet(urlStr); 
  43.                     if (callBack != null
  44.                     { 
  45.                         callBack.onRequestComplete(result); 
  46.                     } 
  47.                 } catch (Exception e) 
  48.                 { 
  49.                     e.printStackTrace(); 
  50.                 } 
  51.  
  52.             }; 
  53.         }.start(); 
  54.     } 
  55.  
  56.     /**
  57.      * 异步的Post请求
  58.      * @param urlStr
  59.      * @param params
  60.      * @param callBack
  61.      * @throws Exception
  62.      */ 
  63.     public static void doPostAsyn(final String urlStr, final String params, 
  64.             final CallBack callBack) throws Exception 
  65.     { 
  66.         new Thread() 
  67.         { 
  68.             public void run() 
  69.             { 
  70.                 try 
  71.                 { 
  72.                     String result = doPost(urlStr, params); 
  73.                     if (callBack != null
  74.                     { 
  75.                         callBack.onRequestComplete(result); 
  76.                     } 
  77.                 } catch (Exception e) 
  78.                 { 
  79.                     e.printStackTrace(); 
  80.                 } 
  81.  
  82.             }; 
  83.         }.start(); 
  84.  
  85.     } 
  86.  
  87.     /**
  88.      * Get请求,获得返回数据
  89.      *
  90.      * @param urlStr
  91.      * @return
  92.      * @throws Exception
  93.      */ 
  94.     public static String doGet(String urlStr)  
  95.     { 
  96.         URL url = null
  97.         HttpURLConnection conn = null
  98.         InputStream is = null
  99.         ByteArrayOutputStream baos = null
  100.         try 
  101.         { 
  102.             url = new URL(urlStr); 
  103.             conn = (HttpURLConnection) url.openConnection(); 
  104.             conn.setReadTimeout(TIMEOUT_IN_MILLIONS); 
  105.             conn.setConnectTimeout(TIMEOUT_IN_MILLIONS); 
  106.             conn.setRequestMethod("GET"); 
  107.             conn.setRequestProperty("accept", "*/*"); 
  108.             conn.setRequestProperty("connection", "Keep-Alive"); 
  109.             if (conn.getResponseCode() == 200
  110.             { 
  111.                 is = conn.getInputStream(); 
  112.                 baos = new ByteArrayOutputStream(); 
  113.                 int len = -1
  114.                 byte[] buf = new byte[128]; 
  115.  
  116.                 while ((len = is.read(buf)) != -1
  117.                 { 
  118.                     baos.write(buf, 0, len); 
  119.                 } 
  120.                 baos.flush(); 
  121.                 return baos.toString(); 
  122.             } else 
  123.             { 
  124.                 throw new RuntimeException(" responseCode is not 200 ... "); 
  125.             } 
  126.  
  127.         } catch (Exception e) 
  128.         { 
  129.             e.printStackTrace(); 
  130.         } finally 
  131.         { 
  132.             try 
  133.             { 
  134.                 if (is != null
  135.                     is.close(); 
  136.             } catch (IOException e) 
  137.             { 
  138.             } 
  139.             try 
  140.             { 
  141.                 if (baos != null
  142.                     baos.close(); 
  143.             } catch (IOException e) 
  144.             { 
  145.             } 
  146.             conn.disconnect(); 
  147.         } 
  148.          
  149.         return null
  150.  
  151.     } 
  152.  
  153.     /** 
  154.      * 向指定 URL 发送POST方法的请求 
  155.      *  
  156.      * @param url 
  157.      *            发送请求的 URL 
  158.      * @param param 
  159.      *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 
  160.      * @return 所代表远程资源的响应结果 
  161.      * @throws Exception 
  162.      */ 
  163.     public static String doPost(String url, String param)  
  164.     { 
  165.         PrintWriter out = null
  166.         BufferedReader in = null
  167.         String result = ""
  168.         try 
  169.         { 
  170.             URL realUrl = new URL(url); 
  171.             // 打开和URL之间的连接 
  172.             HttpURLConnection conn = (HttpURLConnection) realUrl 
  173.                     .openConnection(); 
  174.             // 设置通用的请求属性 
  175.             conn.setRequestProperty("accept", "*/*"); 
  176.             conn.setRequestProperty("connection", "Keep-Alive"); 
  177.             conn.setRequestMethod("POST"); 
  178.             conn.setRequestProperty("Content-Type"
  179.                     "application/x-www-form-urlencoded"); 
  180.             conn.setRequestProperty("charset", "utf-8"); 
  181.             conn.setUseCaches(false); 
  182.             // 发送POST请求必须设置如下两行 
  183.             conn.setDoOutput(true); 
  184.             conn.setDoInput(true); 
  185.             conn.setReadTimeout(TIMEOUT_IN_MILLIONS); 
  186.             conn.setConnectTimeout(TIMEOUT_IN_MILLIONS); 
  187.  
  188.             if (param != null && !param.trim().equals("")) 
  189.             { 
  190.                 // 获取URLConnection对象对应的输出流 
  191.                 out = new PrintWriter(conn.getOutputStream()); 
  192.                 // 发送请求参数 
  193.                 out.print(param); 
  194.                 // flush输出流的缓冲 
  195.                 out.flush(); 
  196.             } 
  197.             // 定义BufferedReader输入流来读取URL的响应 
  198.             in = new BufferedReader( 
  199.                     new InputStreamReader(conn.getInputStream())); 
  200.             String line; 
  201.             while ((line = in.readLine()) != null
  202.             { 
  203.                 result += line; 
  204.             } 
  205.         } catch (Exception e) 
  206.         { 
  207.             e.printStackTrace(); 
  208.         } 
  209.         // 使用finally块来关闭输出流、输入流 
  210.         finally 
  211.         { 
  212.             try 
  213.             { 
  214.                 if (out != null
  215.                 { 
  216.                     out.close(); 
  217.                 } 
  218.                 if (in != null
  219.                 { 
  220.                     in.close(); 
  221.                 } 
  222.             } catch (IOException ex) 
  223.             { 
  224.                 ex.printStackTrace(); 
  225.             } 
  226.         } 
  227.         return result; 
  228.     } 
package com.zhy.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Http请求的工具类
 * 
 * @author zhy
 * 
 */
public class HttpUtils
{

	private static final int TIMEOUT_IN_MILLIONS = 5000;

	public interface CallBack
	{
		void onRequestComplete(String result);
	}


	/**
	 * 异步的Get请求
	 * 
	 * @param urlStr
	 * @param callBack
	 */
	public static void doGetAsyn(final String urlStr, final CallBack callBack)
	{
		new Thread()
		{
			public void run()
			{
				try
				{
					String result = doGet(urlStr);
					if (callBack != null)
					{
						callBack.onRequestComplete(result);
					}
				} catch (Exception e)
				{
					e.printStackTrace();
				}

			};
		}.start();
	}

	/**
	 * 异步的Post请求
	 * @param urlStr
	 * @param params
	 * @param callBack
	 * @throws Exception
	 */
	public static void doPostAsyn(final String urlStr, final String params,
			final CallBack callBack) throws Exception
	{
		new Thread()
		{
			public void run()
			{
				try
				{
					String result = doPost(urlStr, params);
					if (callBack != null)
					{
						callBack.onRequestComplete(result);
					}
				} catch (Exception e)
				{
					e.printStackTrace();
				}

			};
		}.start();

	}

	/**
	 * Get请求,获得返回数据
	 * 
	 * @param urlStr
	 * @return
	 * @throws Exception
	 */
	public static String doGet(String urlStr) 
	{
		URL url = null;
		HttpURLConnection conn = null;
		InputStream is = null;
		ByteArrayOutputStream baos = null;
		try
		{
			url = new URL(urlStr);
			conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
			conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
			conn.setRequestMethod("GET");
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			if (conn.getResponseCode() == 200)
			{
				is = conn.getInputStream();
				baos = new ByteArrayOutputStream();
				int len = -1;
				byte[] buf = new byte[128];

				while ((len = is.read(buf)) != -1)
				{
					baos.write(buf, 0, len);
				}
				baos.flush();
				return baos.toString();
			} else
			{
				throw new RuntimeException(" responseCode is not 200 ... ");
			}

		} catch (Exception e)
		{
			e.printStackTrace();
		} finally
		{
			try
			{
				if (is != null)
					is.close();
			} catch (IOException e)
			{
			}
			try
			{
				if (baos != null)
					baos.close();
			} catch (IOException e)
			{
			}
			conn.disconnect();
		}
		
		return null ;

	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 * @throws Exception
	 */
	public static String doPost(String url, String param) 
	{
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try
		{
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			HttpURLConnection conn = (HttpURLConnection) realUrl
					.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			conn.setRequestProperty("charset", "utf-8");
			conn.setUseCaches(false);
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
			conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);

			if (param != null && !param.trim().equals(""))
			{
				// 获取URLConnection对象对应的输出流
				out = new PrintWriter(conn.getOutputStream());
				// 发送请求参数
				out.print(param);
				// flush输出流的缓冲
				out.flush();
			}
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null)
			{
				result += line;
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally
		{
			try
			{
				if (out != null)
				{
					out.close();
				}
				if (in != null)
				{
					in.close();
				}
			} catch (IOException ex)
			{
				ex.printStackTrace();
			}
		}
		return result;
	}
}

如果大家在使用过程中出现什么错误,或者有更好的建议,欢迎大家留言提出~~可以不断的改进这些类~


源码点击下载

【完美复现】面向配电网韧性提升的移动储能预布局与动态调度策略【IEEE33节点】(Matlab代码实现)内容概要:本文介绍了基于IEEE33节点的配电网韧性提升方法,重点研究了移动储能系统的预布局与动态调度策略。通过Matlab代码实现,提出了一种结合预配置和动态调度的两阶段优化模型,旨在应对电网故障或极端事件时快速恢复供电能力。文中采用了多种智能优化算法(如PSO、MPSO、TACPSO、SOA、GA等)进行对比分析,验证所提策略的有效性和优越性。研究不仅关注移动储能单元的初始部署位置,还深入探讨其在故障发生后的动态路径规划与电力支援过程,从而全面提升配电网的韧性水平。; 适合人群:具备电力系统基础知识和Matlab编程能力的研究生、科研人员及从事智能电网、能源系统优化等相关领域的工程技术人员。; 使用场景及目标:①用于科研复现,特别是IEEE顶刊或SCI一区论文中关于配电网韧性、应急电源调度的研究;②支撑电力系统在灾害或故障条件下的恢复力优化设计,提升实际电网应对突发事件的能力;③为移动储能系统在智能配电网中的应用提供理论依据和技术支持。; 阅读建议:建议读者结合提供的Matlab代码逐模块分析,重点关注目标函数建模、约束条件设置以及智能算法的实现细节。同时推荐参考文中提及的MPS预配置与动态调度上下两部分,系统掌握完整的技术路线,并可通过替换不同算法或测试系统进一步拓展研究。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值