餐饮类-utils

申明源码下载地址:点击打开链接

感谢作者:黄家强 


工具类:CommonUtil

1.GetDistance(获取地球上两点间的距离)
    
    public static double GetDistance(double lat1, double lng1, double lat2,
			double lng2) {
		double EARTH_RADIUS = 6378.137;
		double radLat1 = rad(lat1);
		double radLat2 = rad(lat2);
		double a = radLat1 - radLat2;
		double b = rad(lng1) - rad(lng2);
		double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
				+ Math.cos(radLat1) * Math.cos(radLat2)
				* Math.pow(Math.sin(b / 2), 2)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000;
		return s;
	}	//其中依赖的方法
	private static double rad(double d){
		return d * Math.PI / 180.0;
	}

2.保存图片



    public static void saveMyBitmap(Bitmap mBitmap, String bitName)
			throws IOException {
		File f = new File(Environment.getExternalStorageDirectory()
				+ "/peal_meal/" + bitName + ".png");
		//这一步首次保存文件的时候报目录未找到异常
		File dirFile = new File(Environment.getExternalStorageDirectory()
				+ "/peal_meal/");
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}
		//删除已知同名文件
		if (f.exists()) {
			f.delete();
		}
		//创建新文件
		f.createNewFile();
		FileOutputStream fOut = null;
		try {
			fOut = new FileOutputStream(f);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
		try {
			fOut.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			fOut.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

3.加载图片

	public static Bitmap getImagePath(String bitName) {
		String path = "";
		File f = new File(Environment.getExternalStorageDirectory()
				+ "/peal_meal/" + bitName + ".png");
		try {
			if (f.exists()) {
				path = f.getAbsolutePath();
				FileInputStream fis = new FileInputStream(path);
				return BitmapFactory.decodeStream(fis);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

4.提交表单并上传文件到网站

    /**
	 * 提交表单并上传文件到网站
	 * 
	 * @param url
	 *            提交的接口
	 * @param param
	 *            参数 
     
     <键,值>
      
      
	 * @param bitmap
	 *            图片内容
	 */
	public static String postForm(String url, Map
      
      
       
        param) {
		try {
			HttpPost post = new HttpPost(url);
			HttpClient client = new DefaultHttpClient();
			String BOUNDARY = "*****"; // 边界标识
			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE, BOUNDARY, null);
			if (param != null && !param.isEmpty()) {
				entity.addPart(JsonUtil.IMAGE, new FileBody(new File(param.get(JsonUtil.IMAGE))));
				Log.e("hjq", param.get(JsonUtil.IMAGE));
				entity.addPart(JsonUtil.USER_ID, new StringBody(
						param.get(JsonUtil.USER_ID), Charset.forName("UTF-8")));
				Log.e("hjq", param.get(JsonUtil.USER_ID));
			}
			post.setEntity(entity);

			HttpResponse response;

			response = client.execute(post);

			int stateCode = response.getStatusLine().getStatusCode();
			StringBuffer sb = new StringBuffer();
			if (stateCode == HttpStatus.SC_OK) {
				HttpEntity result = response.getEntity();
				if (result != null) {
					InputStream is = result.getContent();
					BufferedReader br = new BufferedReader(
							new InputStreamReader(is));
					String tempLine;
					while ((tempLine = br.readLine()) != null) {
						sb.append(tempLine);
					}
				}
			}
			post.abort();

			return sb.toString();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
      
      
     
     


工具类:FileUtil

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.List;

import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;

public class FileUtil {

	/**
	 * 删除文件
	 * 
	 * @param context
	 *            程序上下文
	 * @param fileName
	 *            文件名,要在系统内保持唯一
	 * @return boolean 存储成功的标志
	 */
	public static boolean deleteFile(Context context, String fileName) {
		return context.deleteFile(fileName);
	}

	/**
	 * 文件是否存在
	 * 
	 * @param context
	 * @param fileName
	 * @return
	 */
	public static boolean exists(Context context, String fileName) {
		return new File(context.getFilesDir(), fileName).exists();
	}

	/**
	 * 存储文本数据
	 * 
	 * @param context
	 *            程序上下文
	 * @param fileName
	 *            文件名,要在系统内保持唯一
	 * @param content
	 *            文本内容
	 * @return boolean 存储成功的标志
	 */
	public static boolean writeFile(Context context, String fileName,
			String content) {
		boolean success = false;
		FileOutputStream fos = null;
		try {
			fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
			byte[] byteContent = content.getBytes();
			fos.write(byteContent);

			success = true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fos != null)
					fos.close();
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}

		return success;
	}

	/**
	 * 存储文本数据
	 * 
	 * @param context
	 *            程序上下文
	 * @param fileName
	 *            文件名,要在系统内保持唯一
	 * @param content
	 *            文本内容
	 * @return boolean 存储成功的标志
	 */
	public static boolean writeFile(String filePath, String content) {
		boolean success = false;
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(filePath);
			byte[] byteContent = content.getBytes();
			fos.write(byteContent);

			success = true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fos != null)
					fos.close();
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}

		return success;
	}

	/**
	 * 读取文本数据
	 * 
	 * @param context
	 *            程序上下文
	 * @param fileName
	 *            文件名
	 * @return String, 读取到的文本内容,失败返回null
	 */
	public static String readFile(Context context, String fileName) {
		if (!exists(context, fileName)) {
			return null;
		}
		FileInputStream fis = null;
		String content = null;
		try {
			fis = context.openFileInput(fileName);
			if (fis != null) {

				byte[] buffer = new byte[1024];
				ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
				while (true) {
					int readLength = fis.read(buffer);
					if (readLength == -1)
						break;
					arrayOutputStream.write(buffer, 0, readLength);
				}
				fis.close();
				arrayOutputStream.close();
				content = new String(arrayOutputStream.toByteArray());

			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			content = null;
		} finally {
			try {
				if (fis != null)
					fis.close();
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
		return content;
	}

	/**
	 * 读取文本数据
	 * 
	 * @param context
	 *            程序上下文
	 * @param fileName
	 *            文件名
	 * @return String, 读取到的文本内容,失败返回null
	 */
	public static String readFile(String filePath) {
		if (filePath == null || !new File(filePath).exists()) {
			return null;
		}
		FileInputStream fis = null;
		String content = null;
		try {
			fis = new FileInputStream(filePath);
			if (fis != null) {

				byte[] buffer = new byte[1024];
				ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
				while (true) {
					int readLength = fis.read(buffer);
					if (readLength == -1)
						break;
					arrayOutputStream.write(buffer, 0, readLength);
				}
				fis.close();
				arrayOutputStream.close();
				content = new String(arrayOutputStream.toByteArray());

			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			content = null;
		} finally {
			try {
				if (fis != null)
					fis.close();
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
		return content;
	}

	/**
	 * 读取文本数据
	 * 
	 * @param context
	 *            程序上下文
	 * @param fileName
	 *            文件名
	 * @return String, 读取到的文本内容,失败返回null
	 */
	public static String readAssets(Context context, String fileName) {
		InputStream is = null;
		String content = null;
		try {
			is = context.getAssets().open(fileName);
			if (is != null) {

				byte[] buffer = new byte[1024];
				ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
				while (true) {
					int readLength = is.read(buffer);
					if (readLength == -1)
						break;
					arrayOutputStream.write(buffer, 0, readLength);
				}
				is.close();
				arrayOutputStream.close();
				content = new String(arrayOutputStream.toByteArray());

			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			content = null;
		} finally {
			try {
				if (is != null)
					is.close();
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
		return content;
	}

	/**
	 * 存储单个Parcelable对象
	 * 
	 * @param context
	 *            程序上下文
	 * @param fileName
	 *            文件名,要在系统内保持唯一
	 * @param parcelObject
	 *            对象必须实现Parcelable
	 * @return boolean 存储成功的标志
	 */
	public static boolean writeParcelable(Context context, String fileName,
			Parcelable parcelObject) {
		boolean success = false;
		FileOutputStream fos = null;
		try {
			fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
			Parcel parcel = Parcel.obtain();
			parcel.writeParcelable(parcelObject,
					Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
			byte[] data = parcel.marshall();
			fos.write(data);

			success = true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException ioe) {
					ioe.printStackTrace();
				}
			}
		}

		return success;
	}

	/**
	 * 存储List对象
	 * 
	 * @param context
	 *            程序上下文
	 * @param fileName
	 *            文件名,要在系统内保持唯一
	 * @param list
	 *            对象数组集合,对象必须实现Parcelable
	 * @return boolean 存储成功的标志
	 */
	public static boolean writeParcelableList(Context context, String fileName,
			List
     
     
      
       list) {
		boolean success = false;
		FileOutputStream fos = null;
		try {
			if (list instanceof List) {
				fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
				Parcel parcel = Parcel.obtain();
				parcel.writeList(list);
				byte[] data = parcel.marshall();
				fos.write(data);

				success = true;
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException ioe) {
					ioe.printStackTrace();
				}
			}
		}

		return success;
	}

	/**
	 * 读取单个数据对象
	 * 
	 * @param context
	 *            程序上下文
	 * @param fileName
	 *            文件名
	 * @return Parcelable, 读取到的Parcelable对象,失败返回null
	 */
	@SuppressWarnings("unchecked")
	public static Parcelable readParcelable(Context context, String fileName,
			ClassLoader classLoader) {
		Parcelable parcelable = null;
		FileInputStream fis = null;
		ByteArrayOutputStream bos = null;
		try {
			fis = context.openFileInput(fileName);
			if (fis != null) {
				bos = new ByteArrayOutputStream();
				byte[] b = new byte[4096];
				int bytesRead;
				while ((bytesRead = fis.read(b)) != -1) {
					bos.write(b, 0, bytesRead);
				}

				byte[] data = bos.toByteArray();

				Parcel parcel = Parcel.obtain();
				parcel.unmarshall(data, 0, data.length);
				parcel.setDataPosition(0);
				parcelable = parcel.readParcelable(classLoader);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			parcelable = null;
		} finally {
			if (fis != null)
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (bos != null)
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}

		return parcelable;
	}

	/**
	 * 读取数据对象列表
	 * 
	 * @param context
	 *            程序上下文
	 * @param fileName
	 *            文件名
	 * @return List, 读取到的对象数组,失败返回null
	 */
	@SuppressWarnings("unchecked")
	public static List
      
      
       
        readParcelableList(Context context,
			String fileName, ClassLoader classLoader) {
		List
       
       
        
         results = null;
		FileInputStream fis = null;
		ByteArrayOutputStream bos = null;
		try {
			fis = context.openFileInput(fileName);
			if (fis != null) {
				bos = new ByteArrayOutputStream();
				byte[] b = new byte[4096];
				int bytesRead;
				while ((bytesRead = fis.read(b)) != -1) {
					bos.write(b, 0, bytesRead);
				}

				byte[] data = bos.toByteArray();

				Parcel parcel = Parcel.obtain();
				parcel.unmarshall(data, 0, data.length);
				parcel.setDataPosition(0);
				results = parcel.readArrayList(classLoader);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			results = null;
		} finally {
			if (fis != null)
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (bos != null)
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}

		return results;
	}

	public static boolean saveSerializable(Context context, String fileName,
			Serializable data) {
		boolean success = false;
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(context.openFileOutput(fileName,
					Context.MODE_PRIVATE));
			oos.writeObject(data);
			success = true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (oos != null) {
				try {
					oos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return success;
	}

	public static Serializable readSerialLizable(Context context,
			String fileName) {
		Serializable data = null;
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(context.openFileInput(fileName));
			data = (Serializable) ois.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ois != null) {
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return data;
	}

	/**
	 * 从assets里边读取字符串
	 * 
	 * @param context
	 * @param fileName
	 * @return
	 */
	public static String getFromAssets(Context context, String fileName) {
		try {
			InputStreamReader inputReader = new InputStreamReader(context
					.getResources().getAssets().open(fileName));
			BufferedReader bufReader = new BufferedReader(inputReader);
			String line = "";
			String Result = "";
			while ((line = bufReader.readLine()) != null)
				Result += line;
			return Result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 复制文件
	 * 
	 * @param srcFile
	 * @param dstFile
	 * @return
	 */
	public static boolean copy(String srcFile, String dstFile) {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {

			File dst = new File(dstFile);
			if (!dst.getParentFile().exists()) {
				dst.getParentFile().mkdirs();
			}

			fis = new FileInputStream(srcFile);
			fos = new FileOutputStream(dstFile);

			byte[] buffer = new byte[1024];
			int len = 0;

			while ((len = fis.read(buffer)) != -1) {
				fos.write(buffer, 0, len);
			}

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
		return true;
	}

}

       
       
      
      
     
     




工具类:HttpUtil


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;

/**
 * 访问网络的工具类
 *
 *  @author 黄家强
 */
public class HttpUtil {

	/**
	 * 用post方式来访问网络
	 * 
	 * @param url
	 *            要访问的网址
	 * @param nameValuePairs
	 *            需要的参数
	 * @return 网络返回的结果数据
	 */
	public static String post(String url, NameValuePair... nameValuePairs) {
		HttpClient httpClient = new DefaultHttpClient();
		String msg = "";
		HttpPost post = new HttpPost(url);
		List
      
      
       
        params = new ArrayList
       
       
        
        ();
		for (int i = 0; i < nameValuePairs.length; i++) {
			params.add(nameValuePairs[i]);
		}
		try {
			post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			HttpResponse response = httpClient.execute(post);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				msg = EntityUtils.toString(response.getEntity());
			} else {
				Log.e("hjq", "网络请求失败");
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			msg = e.getMessage();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			msg = e.getMessage();
		}
		return msg;
	}

	/**
	 * 用get方式来访问网络
	 * 
	 * @param url
	 *            要访问的网址
	 * @return 网络返回的结果数据
	 */
	public static String get(String url) {
		HttpClient httpClient = new DefaultHttpClient();

		String msg = "";
		HttpGet get = new HttpGet(url);
		HttpResponse response;
		try {
			response = httpClient.execute(get);
			HttpEntity entity = response.getEntity();
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				if (entity != null) {
					BufferedReader br = new BufferedReader(
							new InputStreamReader(entity.getContent()));
					String line = null;
					while ((line = br.readLine()) != null) {
						msg += line;
					}
				}
			} else {
				Log.e("hjq", "网络请求失败");
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return msg;
	}

	private static String getCookie(Context context) {
		CookieSyncManager.createInstance(context);
		CookieManager cookieManager = CookieManager.getInstance();
		String cookie = cookieManager.getCookie("cookie");
		Log.e("hjq", "getCookie=" + cookie);
		return cookie;
	}

	public static String getURlStr(String url, NameValuePair... namevalues) {
		StringBuilder result = new StringBuilder(url + "?");
		for (int i = 0; i < namevalues.length; i++) {
			if (i != 0) {
				result.append("&" + namevalues[i].getName() + "="
						+ namevalues[i].getValue());
			} else {
				result.append(namevalues[i].getName() + "="
						+ namevalues[i].getValue());
			}

		}
		return result.toString();

	}
}

       
       
      
      

工具类:PreferenceUtil


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

/**
 * 
 * 记录用户名,密码之类的首选项
 * 
 */
public class PreferenceUtil {
	private static PreferenceUtil preference = null;
	private SharedPreferences sharedPreference;
	private String packageName = "";
	public static final String USERNAME = "username"; // 登录名
	public static final String PASSWORD = "password"; // 密码
	public static final String REMINDWORD = "remindword"; // 是否保留密码
	public static final String AUTOLOGIN = "autologin";
	public static final String TIMES = "times";
	public static final String UID = "uid";
	public static final String CITY = "city";
	public static final String CITYID = "cityid";
	public static final String LON = "lon";
	public static final String LAT = "lat";
	public static final String SHIBI = "shibi";
	public static final String PHONE = "phone";

	public static synchronized PreferenceUtil getInstance(Context context) {
		if (preference == null)
			preference = new PreferenceUtil(context);
		return preference;
	}

	public PreferenceUtil(Context context) {
		packageName = context.getPackageName() + "_preferences";
		sharedPreference = context.getSharedPreferences(packageName,
				Context.MODE_PRIVATE);
	}

	public String getUid() {
		String value = sharedPreference.getString(UID, "");
		return value;
	}
	public void setUid(String value) {
		Editor edit = sharedPreference.edit();
		edit.putString(UID, value);
		edit.commit();
	}
	public String getString(String name,String defValue) {
		String value = sharedPreference.getString(name, defValue);
		return value;
	}
	public void setString(String name,String value) {
		Editor edit = sharedPreference.edit();
		edit.putString(name, value);
		edit.commit();
	}
	public int getInt(String name,int defValue) {
		int value = sharedPreference.getInt(name,defValue );
		return value;
	}
	public void setInt(String name,int value) {
		Editor edit = sharedPreference.edit();
		edit.putInt(name, value);
		edit.commit();
	}
	public float getFloat(String name,float defValue) {
		float value = sharedPreference.getFloat(name, defValue);
		return value;
	}
	public void setFloat(String name,float value) {
		Editor edit = sharedPreference.edit();
		edit.putFloat(name, value);
		edit.commit();
	}

}

工具类:ThreadPoolManager
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 线程池,管理线程的工具类
 * 
 * @author 黄家强
 */
public class ThreadPoolManager {
	private ExecutorService service;

	private ThreadPoolManager() {
		int num = Runtime.getRuntime().availableProcessors();
		service = Executors.newFixedThreadPool(num * 2);
	}

	private static ThreadPoolManager manager;

	public static ThreadPoolManager getInstance() {
		if (manager == null) {
			manager = new ThreadPoolManager();
		}
		return manager;
	}

	public void addTask(Runnable runnable) {
		service.submit(runnable);
	}
}
工具类:ImageLoaderUtil

import android.content.Context;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

/**
 * 加载图片的工具类
 * 
 * @author 黄家强
 */
public class ImageLoaderUtil {
	public static DisplayImageOptions options_image, options_progress,
			options_grid;
	private static ImageLoader imageLoader;

	private static void initLoader(Context context) {
		options_image = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.defaultpic)
				.showImageForEmptyUri(R.drawable.defaultpic).cacheInMemory()
				.cacheOnDisc().imageScaleType(ImageScaleType.POWER_OF_2)
				.displayer(new RoundedBitmapDisplayer(0xff424242, 10)).build();
		options_progress = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(R.drawable.defaultpic).cacheOnDisc()
				.imageScaleType(ImageScaleType.EXACT).build();
		imageLoader = ImageLoader.getInstance();
		imageLoader.init(ImageLoaderConfiguration.createDefault(context));
		options_grid = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.defaultpic)
				.showImageForEmptyUri(R.drawable.defaultpic).cacheInMemory()
				.cacheOnDisc().build();
	}

	public static ImageLoader getImageLoader(Context context) {
		if (imageLoader == null) {
			initLoader(context);
		}
		return imageLoader;
	}

	public static void displayImage(String url, ImageView imageView,
			Context context) {
		getImageLoader(context).displayImage(url, imageView, options_image);
	}

	public static void displayImage(String url, ImageView imageView,
			Context context, DisplayImageOptions options) {
		getImageLoader(context).displayImage(url, imageView, options);
	}

	public static void displayImage(String url, ImageView imageView,
			Context context, DisplayImageOptions options,
			ImageLoadingListener imageLoadingListener) {
		getImageLoader(context).displayImage(url, imageView, options,
				imageLoadingListener);
	}

	public static void stopload(Context context) {
		getImageLoader(context).stop();
	}
}
工具类: 软件更新工具类

package com.zsct.customer.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.fdcz.zsct.R;
import com.zsct.customer.app.MyApplication;


public class UpdateManager {
	private Context mContext;
	// 提示语
	private String updateMsg;
	// 返回的安装包url
	private String apkUrl;
	private Dialog noticeDialog;
	private Dialog downloadDialog;
	/* 下载包安装路径 */
	private static final String savePath = Environment
			.getExternalStorageDirectory().getPath() + "/peal_meal/";
	private static final String apkname = "customer.apk";
	private static final String saveFileName = savePath + apkname;
	/* 进度条与通知ui刷新的handler和msg常量 */
	private boolean ishide = false;
	private ProgressBar mProgress;
	private TextView mTextView;
	private Notification downloadNotification;
	private NotificationManager downloadNM;
	private static final int DOWN_UPDATE = 1;
	private static final int DOWN_OVER = 2;
	private int downNotiID = 21;
	private int progress = 0;
	private boolean interceptFlag = false;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWN_UPDATE:
				if (ishide) {
					updateProgress(progress);
				} else {
					mProgress.setProgress(progress);
				}
				break;
			case DOWN_OVER:
				if (ishide) {
					downloadNM.cancel(downNotiID);
				} else {
					downloadDialog.cancel();
				}
				installApk();
				break;
			default:
				break;
			}
		};
	};

	public UpdateManager(Context context, String updatemsg, String dlurl) {
		this.mContext = context;
		this.updateMsg = getUpdateMsg(updatemsg);
		this.apkUrl = dlurl;
	}

	public void showNoticeDialog() {
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle(R.string.software_update);
		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.update, null);
		mTextView = (TextView) v.findViewById(R.id.update_msg);
		mTextView.setText(updateMsg);
		builder.setView(v);
		builder.setPositiveButton(R.string.download, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				noticeDialog.dismiss();
				showDownloadDialog();
			}
		});
		builder.setNegativeButton(R.string.system_exit, new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				MyApplication.getInstance().exit();
			}
		}).setCancelable(false);
		noticeDialog = builder.create();
		noticeDialog.show();
	}

	private String getUpdateMsg(String msg) {
		// TODO Auto-generated method stub
		if (!msg.equals("") && msg.length() > 0) {
			msg = msg.replace(";", "\n");
		}
		return msg;
	}

	public  void showDownloadDialog() {
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle(R.string.software_update);
		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.update, null);
		mProgress = (ProgressBar) v.findViewById(R.id.progress);
		mTextView = (TextView) v.findViewById(R.id.update_msg);
		mTextView.setText(updateMsg);
		mProgress.setVisibility(View.VISIBLE);
		builder.setView(v).setCancelable(false);
		 builder.setPositiveButton(R.string.hide, new OnClickListener() {
		 @Override
		 public void onClick(DialogInterface dialog, int which) {
		 downloadDialog.dismiss();
		 initNotif();
		 ishide = true;
		 }
		 });
		 builder.setNegativeButton(R.string.system_cancel, new OnClickListener() {
		 @Override
		 public void onClick(DialogInterface dialog, int which) {
		 downloadDialog.dismiss();
		 interceptFlag = true;
		 }
		 });
		downloadDialog = builder.create();
		downloadDialog.show();
		downloadApk();
	}

	private Runnable mdownApkRunnable = new Runnable() {
		@Override
		public void run() {
			try {
				URL url = new URL(apkUrl);

				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.connect();
				int length = conn.getContentLength();
				InputStream is = conn.getInputStream();

				File file = new File(savePath);
				if (!file.exists()) {
					file.mkdir();
				}
				String apkFile = saveFileName;
				File ApkFile = new File(apkFile);
				FileOutputStream fos = new FileOutputStream(ApkFile);

				int count = 0;
				byte buf[] = new byte[1024];
				Timer mTimer = new Timer();
				mTimer.schedule(new TimerTask() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						mHandler.sendEmptyMessage(DOWN_UPDATE);
					}
				}, 0, 1000);

				do {
					int numread = is.read(buf);
					count += numread;
					progress = (int) (((float) count / length) * 100);
					// 更新进度

					// mHandler.sendEmptyMessage(DOWN_UPDATE);
					if (numread <= 0) {
						// 下载完成通知安装
						mHandler.sendEmptyMessage(DOWN_UPDATE);
						mHandler.sendEmptyMessage(DOWN_OVER);
						mTimer.cancel();
						break;
					}
					fos.write(buf, 0, numread);
				} while (!interceptFlag);// 点击取消就停止下载.
				mTimer.cancel();
				fos.close();
				is.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	};

	@SuppressWarnings("deprecation")
	public void initNotif() {
		downloadNM = (NotificationManager) mContext
				.getSystemService(Context.NOTIFICATION_SERVICE);
		downloadNotification = new Notification(R.drawable.ic_launcher, apkname
				+ mContext.getResources().getString(R.string.download),
				System.currentTimeMillis());
		downloadNotification.contentView = new RemoteViews(
				mContext.getPackageName(), R.layout.notification);
		// 显示下载的包名
		downloadNotification.contentView.setTextViewText(R.id.down_tv, apkname);
		// 显示下载的进度
		downloadNotification.contentView.setTextViewText(R.id.down_rate, "0%");
		downloadNotification.flags |= Notification.FLAG_AUTO_CANCEL;
		downloadNM.notify(downNotiID, downloadNotification);
	}

	public void updateProgress(int progress) {
		downloadNotification.contentView.setTextViewText(R.id.down_rate,
				progress + "%");
		downloadNM.notify(downNotiID, downloadNotification);

	}

	/**
	 * 下载apk
	 * 
	 * @param url
	 */

	private void downloadApk() {
		ThreadPoolManager.getInstance().addTask(mdownApkRunnable);
	}

	/**
	 * 安装apk
	 * 
	 * @param url
	 */
	private void installApk() {
		File apkfile = new File(saveFileName);
		if (!apkfile.exists()) {
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
				"application/vnd.android.package-archive");
		mContext.startActivity(i);

	}
}












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值