Android开发中常用的工具类整理

2015-05-11 13:30:44 768浏览

     昨天看到一个好的整理帖子,是关于Android开发中常用的工具类整理,整理得很好,其中包括日志、Toast网络、像素单位转换、屏幕、App相关、键盘、文件上传下载、加密、时间等工具类,特意分享给大家。希望大家喜欢的话,可以顶顶帖子,让更多人看到,谢谢。


日志类

1. 




1.	package net.wujingchao.android.utility
2.	
3.	import android.util.Log;
4.	
5.	public final class L {
6.	
7.	private final static int LEVEL = 5;
8.	
9.	private final static String DEFAULT_TAG = "L";
10.	
11.	private L() {
12.	throw new UnsupportedOperationException("L cannot instantiated!");
13.	}
14.	
15.	public static void v(String tag,String msg) {
16.	if(LEVEL >= 5)Log.v(tag == null ? DEFAULT_TAG:tag,msg == null?"":msg);
17.	}
18.	
19.	public static void d(String tag,String msg) {
20.	if(LEVEL >= 4)Log.d(tag == null ? DEFAULT_TAG:tag,msg == null?"":msg);
21.	}
22.	
23.	public static void i(String tag,String msg) {
24.	if(LEVEL >= 3)Log.i(tag == null ? DEFAULT_TAG:tag,msg == null?"":msg);
25.	}
26.	
27.	public static void w(String tag,String msg) {
28.	if(LEVEL >= 2)Log.w(tag == null ? DEFAULT_TAG:tag,msg == null?"":msg);
29.	}
30.	
31.	public static void e(String tag,String msg) {
32.	if(LEVEL >= 1)Log.e(tag == null ? DEFAULT_TAG:tag,msg == null?"":msg);
33.	}
34.	}
35.	Toast

1.	package net.wujingchao.android.utility 
2.	
3.	import android.content.Context;
4.	import android.widget.Toast;
5.	
6.	public class T {
7.	
8.	private final static boolean isShow = true;
9.	
10.	private T(){
11.	throw new UnsupportedOperationException("T cannot be instantiated");
12.	}
13.	
14.	public static void showShort(Context context,CharSequence text) {
15.	if(isShow)Toast.makeText(context,text,Toast.LENGTH_SHORT).show();
16.	}
17.	
18.	public static void showLong(Context context,CharSequence text) {
19.	if(isShow)Toast.makeText(context,text,Toast.LENGTH_LONG).show();
20.	}
21.	}



网络类
1.	package net.wujingchao.android.utility
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.	import javax.net.ssl.HttpsURLConnection;
11.	import javax.net.ssl.SSLContext;
12.	import javax.net.ssl.TrustManager;
13.	import javax.net.ssl.X509TrustManager;
14.	
15.	public class NetworkUtil {
16.	
17.	private NetworkUtil() {
18.	throw new UnsupportedOperationException("NetworkUtil cannot be instantiated");
19.	}
20.	
21.	/**
22.	* 判断网络是否连接
23.	*
24.	*/
25.	public static boolean isConnected(Context context) {
26.	ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
27.	if (null != connectivity) {
28.	NetworkInfo info = connectivity.getActiveNetworkInfo();
29.	if (null != info && info.isConnected()){
30.	if (info.getState() == NetworkInfo.State.CONNECTED) {
31.	return true;
32.	}
33.	}
34.	}
35.	return false;
36.	}
37.	
38.	/**
39.	* 判断是否是wifi连接
40.	*/
41.	public static boolean isWifi(Context context){
42.	ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
43.	if (connectivity == null) return false;
44.	return connectivity.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;
45.	
46.	}
47.	
48.	/**
49.	* 打开网络设置界面
50.	*/
51.	public static void openSetting(Activity activity) {
52.	Intent intent = new Intent("/");
53.	ComponentName componentName = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
54.	intent.setComponent(componentName);
55.	intent.setAction("android.intent.action.VIEW");
56.	activity.startActivityForResult(intent, 0);
57.	}
58.	
59.	/**
60.	* 使用SSL不信任的证书
61.	*/
62.	public static void useUntrustedCertificate() {
63.	// Create a trust manager that does not validate certificate chains
64.	TrustManager[] trustAllCerts = new TrustManager[]{
65.	new X509TrustManager() {
66.	public java.security.cert.X509Certificate[] getAcceptedIssuers() {
67.	return null;
68.	}
69.	public void checkClientTrusted(
70.	java.security.cert.X509Certificate[] certs, String authType) {
71.	}
72.	public void checkServerTrusted(
73.	java.security.cert.X509Certificate[] certs, String authType) {
74.	}
75.	}
76.	};
77.	// Install the all-trusting trust manager
78.	try {
79.	SSLContext sc = SSLContext.getInstance("SSL");
80.	sc.init(null, trustAllCerts, new java.security.SecureRandom());
81.	HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
82.	} catch (Exception e) {
83.	e.printStackTrace();
84.	}
85.	}
86.	}


App相关类
1.	package net.wujingchao.android.utility 
2.	
3.	import android.content.Context;
4.	import android.content.pm.PackageInfo;
5.	import android.content.pm.PackageManager;
6.	
7.	public class AppUtil {
8.	
9.	private AppUtil() {
10.	throw new UnsupportedOperationException("AppUtil cannot instantiated");
11.	}
12.	
13.	/**
14.	* 获取app版本名
15.	*/
16.	public static String getAppVersionName(Context context){
17.	PackageManager pm = context.getPackageManager();
18.	PackageInfo pi;
19.	try {
20.	pi = pm.getPackageInfo(context.getPackageName(),0);
21.	return pi.versionName;
22.	} catch (PackageManager.NameNotFoundException e) {
23.	e.printStackTrace();
24.	}
25.	return "";
26.	}
27.	
28.	/**
29.	* 获取应用程序版本名称信息
30.	*/
31.	public static String getVersionName(Context context)
32.	{
33.	try{
34.	PackageManager packageManager = context.getPackageManager();
35.	PackageInfo packageInfo = packageManager.getPackageInfo(
36.	context.getPackageName(), 0);
37.	return packageInfo.versionName;
38.	}catch (PackageManager.NameNotFoundException e) {
39.	e.printStackTrace();
40.	}
41.	return null;
42.	}
43.	
44.	/**
45.	* 获取app版本号
46.	*/
47.	public static int getAppVersionCode(Context context){
48.	PackageManager pm = context.getPackageManager();
49.	PackageInfo pi;
50.	try {
51.	pi = pm.getPackageInfo(context.getPackageName(),0);
52.	return pi.versionCode;
53.	} catch (PackageManager.NameNotFoundException e) {
54.	e.printStackTrace();
55.	}
56.	return 0;
57.	}
58.	}


键盘类
1.	package net.wujingchao.android.utility
2.	
3.	import android.content.Context;
4.	import android.view.inputmethod.InputMethodManager;
5.	import android.widget.EditText;
6.	
7.	public class KeyBoardUtil{
8.	
9.	private KeyBoardUtil(){
10.	throw new UnsupportedOperationException("KeyBoardUtil cannot be instantiated");
11.	}
12.	
13.	/**
14.	* 打卡软键盘
15.	*/
16.	public static void openKeybord(EditText mEditText, Context mContext){
17.	InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
18.	imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
19.	imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);
20.	}
21.	/**
22.	* 关闭软键盘
23.	*/
24.	public static void closeKeybord(EditText mEditText, Context mContext) {
25.	InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
26.	imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
27.	}
28.	}


文件上传下载类
1.	package net.wujingchao.android.utility
2.	
3.	import android.content.Context;
4.	import android.os.Environment;
5.	
6.	import java.io.ByteArrayOutputStream;
7.	import java.io.DataOutputStream;
8.	import java.io.File; 
9.	import java.io.FileInputStream;
10.	import java.io.FileNotFoundException;
11.	import java.io.IOException;
12.	import java.io.InputStream; 
13.	import java.io.OutputStream;
14.	import java.net.HttpURLConnection;
15.	import java.net.MalformedURLException;
16.	import java.net.ProtocolException;
17.	import java.net.URL;
18.	import java.util.UUID;
19.	
20.	import com.mixiaofan.App;
21.	
22.	public class DownloadUtil {
23.	
24.	private static final int TIME_OUT = 30*1000; //超时时间
25.	
26.	private static final String CHARSET = "utf-8"; //设置编码
27.	
28.	private DownloadUtil() {
29.	throw new UnsupportedOperationException("DownloadUtil cannot be instantiated");
30.	}
31.	
32.	/**
33.	* @param file 上传文件
34.	* @param RequestURL 上传文件URL
35.	* @return 服务器返回的信息,如果出错则返回为null
36.	*/
37.	public static String uploadFile(File file,String RequestURL) {
38.	String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成 String PREFIX = "--" , LINE_END = "\r\n";
39.	String PREFIX = "--" , LINE_END = "\r\n";
40.	String CONTENT_TYPE = "multipart/form-data"; //内容类型
41.	try {
42.	URL url = new URL(RequestURL);
43.	HttpURLConnection conn = (HttpURLConnection) url.openConnection();
44.	conn.setReadTimeout(TIME_OUT);
45.	conn.setConnectTimeout(TIME_OUT);
46.	conn.setDoInput(true); //允许输入流
47.	conn.setDoOutput(true); //允许输出流
48.	conn.setUseCaches(false); //不允许使用缓存 
49.	conn.setRequestMethod("POST"); //请求方式 
50.	conn.setRequestProperty("Charset", CHARSET);
51.	conn.setRequestProperty("Cookie", "PHPSESSID=" + App.getSessionId());
52.	//设置编码 
53.	conn.setRequestProperty("connection", "keep-alive"); 
54.	conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
55.	if(file!=null) { 
56.	/** * 当文件不为空,把文件包装并且上传 */
57.	OutputStream outputSteam=conn.getOutputStream();
58.	DataOutputStream dos = new DataOutputStream(outputSteam);
59.	StringBuffer sb = new StringBuffer();
60.	sb.append(PREFIX);
61.	sb.append(BOUNDARY); sb.append(LINE_END);
62.	/**
63.	* 这里重点注意:
64.	* name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
65.	* filename是文件的名字,包含后缀名的 比如:abc.png
66.	*/
67.	sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END);
68.	sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END);
69.	sb.append(LINE_END);
70.	dos.write(sb.toString().getBytes());
71.	InputStream is = new FileInputStream(file);
72.	byte[] bytes = new byte[1024];
73.	int len;
74.	while((len=is.read(bytes))!=-1)
75.	{
76.	dos.write(bytes, 0, len);
77.	}
78.	is.close();
79.	dos.write(LINE_END.getBytes());
80.	byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
81.	dos.write(end_data);
82.	dos.flush();
83.	/**
84.	* 获取响应码 200=成功
85.	* 当响应成功,获取响应的流
86.	*/
87.	ByteArrayOutputStream bos = new ByteArrayOutputStream();
88.	InputStream resultStream = conn.getInputStream();
89.	len = -1;
90.	byte [] buffer = new byte[1024*8];
91.	while((len = resultStream.read(buffer)) != -1) {
92.	bos.write(buffer,0,len);
93.	}
94.	resultStream.close();
95.	bos.flush();
96.	bos.close();
97.	String info = new String(bos.toByteArray());
98.	int res = conn.getResponseCode();
99.	if(res==200){
100.	return info;
101.	}else {
102.	return null;
103.	}
104.	}
105.	} catch (MalformedURLException e) {
106.	e.printStackTrace();
107.	} catch (ProtocolException e) {
108.	e.printStackTrace();
109.	} catch (FileNotFoundException e) {
110.	e.printStackTrace();
111.	} catch (IOException e) {
112.	e.printStackTrace();
113.	}
114.	return null;
115.	}


1.	public static byte[] download(String urlStr) {
2.	HttpURLConnection conn = null;
3.	InputStream is = null;
4.	byte[] result = null;
5.	ByteArrayOutputStream bos = null;
6.	try {
7.	URL url = new URL(urlStr);
8.	conn = (HttpURLConnection) url.openConnection();
9.	conn.setRequestMethod("GET");
10.	conn.setConnectTimeout(TIME_OUT);
11.	conn.setReadTimeout(TIME_OUT);
12.	conn.setDoInput(true);
13.	conn.setUseCaches(false);//不使用缓存
14.	if(conn.getResponseCode() == 200) {
15.	is = conn.getInputStream();
16.	byte [] buffer = new byte[1024*8];
17.	int len;
18.	bos = new ByteArrayOutputStream();
19.	while((len = is.read(buffer)) != -1) {
20.	bos.write(buffer,0,len);
21.	}
22.	bos.flush();
23.	result = bos.toByteArray();
24.	}
25.	} catch (MalformedURLException e) {
26.	e.printStackTrace();
27.	} catch (IOException e) {
28.	e.printStackTrace();
29.	} finally {
30.	try {
31.	if(bos != null){
32.	bos.close();
33.	}
34.	if (is != null) {
35.	is.close();
36.	}
37.	if (conn != null)conn.disconnect();
38.	} catch (IOException e) {
39.	e.printStackTrace();
40.	}
41.	}
42.	return result;
43.	}
44.	
45.	/**
46.	* 获取缓存文件
47.	*/
48.	public static File getDiskCacheFile(Context context,String filename,boolean isExternal) {
49.	if(isExternal && (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))) {
50.	return new File(context.getExternalCacheDir(),filename);
51.	}else {
52.	return new File(context.getCacheDir(),filename);
53.	}
54.	}
55.	
56.	/**
57.	* 获取缓存文件目录
58.	*/
59.	public static File getDiskCacheDirectory(Context context) {
60.	if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
61.	return context.getExternalCacheDir();
62.	}else {
63.	return context.getCacheDir();
64.	}
65.	}
66.	}


加密类
1.	package net.wujingchao.android.utility
2.	
3.	import java.security.MessageDigest;
4.	import java.security.NoSuchAlgorithmException;
5.	
6.	public class CipherUtil { 
7.	
8.	private CipherUtil() {
9.	
10.	}
11.	
12.	//字节数组转化为16进制字符串
13.	public static String byteArrayToHex(byte[] byteArray) {
14.	char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F' };
15.	char[] resultCharArray =new char[byteArray.length * 2];
16.	int index = 0;
17.	for (byte b : byteArray) {
18.	resultCharArray[index++] = hexDigits[b>>> 4 & 0xf];
19.	resultCharArray[index++] = hexDigits[b & 0xf];
20.	}
21.	return new String(resultCharArray);
22.	}
23.	
24.	//字节数组md5算法
25.	public static byte[] md5 (byte [] bytes) {
26.	try {
27.	MessageDigest messageDigest = MessageDigest.getInstance("MD5");
28.	messageDigest.update(bytes);
29.	return messageDigest.digest();
30.	} catch (NoSuchAlgorithmException e) {
31.	e.printStackTrace();
32.	}
33.	return null;
34.	}
35.	}


标签:

热门专区

暂无热门资讯

课程推荐

微信
微博
15311698296

全国免费咨询热线

邮箱:codingke@1000phone.com

官方群:148715490

北京千锋互联科技有限公司版权所有   北京市海淀区宝盛北里西区28号中关村智诚科创大厦4层
京ICP备12003911号-6   Copyright © 2013 - 2019

京公网安备 11010802030908号