工具类
来源:互联网 发布:广州java招聘 编辑:程序博客网 时间:2024/06/05 23:45
import android.util.Log;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.message.BasicNameValuePair;import org.apache.http.params.BasicHttpParams;import org.apache.http.params.HttpConnectionParams;import org.apache.http.params.HttpParams;import org.apache.http.protocol.HTTP;import org.apache.http.util.EntityUtils;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.Map;/** * Created by Admin on 2017/3/14. * 网络请求工具类 */public class HttpClientUtil { private static final int RetryTime = 3; private static int connectTimes = 1 ; private static String TAG = "HttpClientUtil"; /** * HttpGet方法请求 * @param url */ public static void httpGetReq(final String url, final HttpReqListener listener){ Log.i(TAG, "httpGetReq: url = " + url); new Thread(new Runnable() { @Override public void run() { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); // 设置Http参数 HttpParams httpParams = new BasicHttpParams(); // 超时连接10秒钟断开连接 HttpConnectionParams.setConnectionTimeout(httpParams,10 * 1000); // 设置超时连接 HttpConnectionParams.setSoTimeout(httpParams,10 * 1000); httpGet.setParams(httpParams); try { HttpResponse httpResponse = httpClient.execute(httpGet); String result; // 服务器有响应 if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ result = EntityUtils.toString(httpResponse.getEntity(),"utf-8"); if(listener != null) connectTimes = 1; listener.HttpReqSuccece(result); } } catch (IOException e) { Log.i(TAG, "run: httpGetException "); // 连接失败重连3次 if(connectTimes <= RetryTime){ connectTimes ++ ; try { Thread.sleep(5000); } catch (InterruptedException e1) { e1.printStackTrace(); } httpGetReq(url,listener); return; } connectTimes = 1; if(listener != null){ listener.HttpReqFail("Connect Fail"); } e.printStackTrace(); } } }).start(); } /** * http post请求 参数是key - Value形式 * @param url 接口 * @param map 参数key - value map * @param listener 回调接口 */ public static void httpReqPost(final String url ,final Map<String , String> map , final HttpReqListener listener){ new Thread(new Runnable() { @Override public void run() { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams,10 * 1000); HttpConnectionParams.setSoTimeout(httpParams , 10 * 1000); httpPost.setParams(httpParams); List<NameValuePair> params = new ArrayList<>(); Iterator iterator = map.entrySet().iterator(); while (iterator.hasNext()){ Map.Entry entry = (Map.Entry) iterator.next(); String key = (String) entry.getKey(); String value = (String) entry.getKey(); params.add(new BasicNameValuePair(key,value)); } try { httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse response = httpClient.execute(httpPost); if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ String result = EntityUtils.toString(response.getEntity(),"utf-8"); if(listener != null){ connectTimes = 1; listener.HttpReqSuccece(result); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { // 连接失败重连3次 if(connectTimes <= RetryTime){ connectTimes ++ ; try { Thread.sleep(5000); } catch (InterruptedException e1) { e1.printStackTrace(); } httpReqPost(url , map , listener); return; } connectTimes = 1; if(listener != null){ listener.HttpReqFail("Connect Fail"); } e.printStackTrace(); } } }).start(); } /** * 网络请求接口回调 */ public interface HttpReqListener{ void HttpReqSuccece(String result); void HttpReqFail(String error); }}** * 判断包是否安装 * * @param context * @param packageName * @return */ public static boolean isInstalled(Context context, String packageName) { PackageManager manager = context.getPackageManager(); try { manager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES); return true; } catch (PackageManager.NameNotFoundException e) { return false; } } /** * 安装应用程序 * * @param context * @param apkFile */ public static void installApp(Context context, File apkFile) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive"); context.startActivity(intent); } /** * 打开应用程序 * * @param context * @param packageName */ public static void openApp(Context context, String packageName) { Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName); context.startActivity(intent); }
LOG打印
import android.text.TextUtils;import android.util.Log;import com.itheima.googleplay_27.conf.Constants;import java.util.List;/** * @ * @time 2015-6-23 上午11:33:49 * @des 日志级别是LEVEL_ALL显示所有信息, 包括System.out.println信息 * @des 日志级别是LEVEL_OFF关闭所有信息, 包括System.out.println信息 * @updateAuthor TODO * @updateTime TODO * @updateDes TODO */public class LogUtils { /** * 日志输出时的TAG */ private static String mTag = "GooglePlay"; /** * 日志输出级别NONE */ public static final int LEVEL_OFF = 0; /** * 日志输出级别NONE */ public static final int LEVEL_ALL = 7; /** * 日志输出级别V */ public static final int LEVEL_VERBOSE = 1; /** * 日志输出级别D */ public static final int LEVEL_DEBUG = 2; /** * 日志输出级别I */ public static final int LEVEL_INFO = 3; /** * 日志输出级别W */ public static final int LEVEL_WARN = 4; /** * 日志输出级别E */ public static final int LEVEL_ERROR = 5; /** * 日志输出级别S,自定义定义的一个级别 */ public static final int LEVEL_SYSTEM = 6; /** * 是否允许输出log */ private static int mDebuggable = Constants.DEBUGLEVEL; /** * 用于记时的变量 */ private static long mTimestamp = 0; /** * 写文件的锁对象 */ private static final Object mLogLock = new Object(); /**---------------日志输出,已固定TAG begin---------------**/ /** * 以级别为 d 的形式输出LOG */ public static void v(String msg) { if (mDebuggable >= LEVEL_VERBOSE) { Log.v(mTag, msg); } } /** * 以级别为 d 的形式输出LOG */ public static void d(String msg) { if (mDebuggable >= LEVEL_DEBUG) { Log.d(mTag, msg); } } /** * 以级别为 i 的形式输出LOG */ public static void i(String msg) { if (mDebuggable >= LEVEL_INFO) { Log.i(mTag, msg); } } /** * 以级别为 w 的形式输出LOG */ public static void w(String msg) { if (mDebuggable >= LEVEL_WARN) { Log.w(mTag, msg); } } /** * 以级别为 w 的形式输出Throwable */ public static void w(Throwable tr) { if (mDebuggable >= LEVEL_WARN) { Log.w(mTag, "", tr); } } /** * 以级别为 w 的形式输出LOG信息和Throwable */ public static void w(String msg, Throwable tr) { if (mDebuggable >= LEVEL_WARN && null != msg) { Log.w(mTag, msg, tr); } } /** * 以级别为 e 的形式输出LOG */ public static void e(String msg) { if (mDebuggable >= LEVEL_ERROR) { Log.e(mTag, msg); } } /** * 以级别为 s 的形式输出LOG,主要是为了System.out.println,稍微格式化了一下 */ public static void sf(String msg) { if (mDebuggable >= LEVEL_ERROR) { System.out.println("----------" + msg + "----------"); } } /** * 以级别为 s 的形式输出LOG,主要是为了System.out.println */ public static void s(String msg) { if (mDebuggable >= LEVEL_ERROR) { System.out.println(msg); } } /** * 以级别为 e 的形式输出Throwable */ public static void e(Throwable tr) { if (mDebuggable >= LEVEL_ERROR) { Log.e(mTag, "", tr); } } /** * 以级别为 e 的形式输出LOG信息和Throwable */ public static void e(String msg, Throwable tr) { if (mDebuggable >= LEVEL_ERROR && null != msg) { Log.e(mTag, msg, tr); } } /**---------------日志输出,已固定TAG end---------------**/ /**---------------日志输出,未固定TAG begin---------------**/ /** * 以级别为 d 的形式输出LOG */ public static void v(String tag, String msg) { if (mDebuggable >= LEVEL_VERBOSE) { Log.v(tag, msg); } } /** * 以级别为 d 的形式输出LOG */ public static void d(String tag, String msg) { if (mDebuggable >= LEVEL_DEBUG) { Log.d(tag, msg); } } /** * 以级别为 i 的形式输出LOG */ public static void i(String tag, String msg) { if (mDebuggable >= LEVEL_INFO) { Log.i(tag, msg); } } /** * 以级别为 w 的形式输出LOG */ public static void w(String tag, String msg) { if (mDebuggable >= LEVEL_WARN) { Log.w(tag, msg); } } /** * 以级别为 e 的形式输出LOG */ public static void e(String tag, String msg) { if (mDebuggable >= LEVEL_ERROR) { Log.e(tag, msg); } } /**---------------日志输出,未固定TAG end---------------**/ /** * 把Log存储到文件中 * * @param log 需要存储的日志 * @param path 存储路径 */ public static void log2File(String log, String path) { log2File(log, path, true); } public static void log2File(String log, String path, boolean append) { synchronized (mLogLock) { FileUtils.writeFile(log + "\r\n", path, append); } } /** * 以级别为 e 的形式输出msg信息,附带时间戳,用于输出一个时间段起始点 * * @param msg 需要输出的msg */ public static void msgStartTime(String msg) { mTimestamp = System.currentTimeMillis(); if (!TextUtils.isEmpty(msg)) { e("[Started:" + mTimestamp + "]" + msg); } } /** * 以级别为 e 的形式输出msg信息,附带时间戳,用于输出一个时间段结束点* @param msg 需要输出的msg */ public static void elapsed(String msg) { long currentTime = System.currentTimeMillis(); long elapsedTime = currentTime - mTimestamp; mTimestamp = currentTime; e("[Elapsed:" + elapsedTime + "]" + msg); } public static <T> void printList(List<T> list) { if (list == null || list.size() < 1) { return; } int size = list.size(); i("---begin---"); for (int i = 0; i < size; i++) { i(i + ":" + list.get(i).toString()); } i("---end---"); } public static <T> void printArray(T[] array) { if (array == null || array.length < 1) { return; } int length = array.length; i("---begin---"); for (int i = 0; i < length; i++) { i(i + ":" + array[i].toString()); } i("---end---"); }}
UI相关import android.content.Context;import android.content.res.Resources;import com.itheima.googleplay_27.MyApplication;/** * 类 名: UIUtils * 创 建 者: * 创建时间: 2016/8/20 10:59 * 描 述:常见的一些和ui操作相关的方法 */public class UIUtils { /** * 得到上下文 * * @return */ public static Context getContext() { return MyApplication.getContext(); } /** * 得到Resource对象 */ public static Resources getResources() { return getContext().getResources(); } /** * 得到String.xml中定义的字符串信息 */ public static String getString(int resId) { return getResources().getString(resId); } /** * 得到String.xml中定义的字符串数组信息 */ public static String[] getStrings(int resId) { return getResources().getStringArray(resId); } /** * 得到Color.xml中定义的颜色信息 */ public static int getColor(int resId) { return getResources().getColor(resId); } /** * 得到应用程序的包名 * * @return */ public static String getPackageName() { return getContext().getPackageName(); } /** * dp-->px * * @param dp * @return */ public static int dp2Px(int dp) { //dp和px相互转换的公式 //公式一:px/dp = density //公式二:px/(ppi/160) = dp /* 480x800 ppi=240 1.5 1280x720 ppi = 320 2 */ float density = getResources().getDisplayMetrics().density; int px = (int) (dp * density + .5f); return px; } /** * px-->do * * @param px * @return */ public static int px2Dp(int px) { //dp和px相互转换的公式 //公式一:px/dp = density //公式二:px/(ppi/160) = dp /* 480x800 ppi=240 1.5 1280x720 ppi = 320 2 */ float density = getResources().getDisplayMetrics().density; int dp = (int) (px / density + .5f); return dp; } /** * sp-->px * * @param spValue * @return */ public static int sp2px(float spValue) { final float fontScale = getResources().getDisplayMetrics().scaledDensity; return (int) (spValue * fontScale + 0.5f); }}文件
import android.os.Environment;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.RandomAccessFile;import java.util.HashMap;import java.util.Map;import java.util.Properties;/** * * @author 写文件的工具类 * */public class FileUtils {public static final String ROOT_DIR = "Android/data/"+ UIUtils.getPackageName();public static final String DOWNLOAD_DIR = "download";public static final String CACHE_DIR = "cache";public static final String ICON_DIR = "icon";/** 判断SD卡是否挂载 */public static boolean isSDCardAvailable() {if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {return true;} else {return false;}}/** 获取下载目录 */public static String getDownloadDir() {return getDir(DOWNLOAD_DIR);}/** 获取缓存目录 */public static String getCacheDir() {return getDir(CACHE_DIR);}/** 获取icon目录 */public static String getIconDir() {return getDir(ICON_DIR);}/** 获取应用目录,当SD卡存在时,获取SD卡上的目录,当SD卡不存在时,获取应用的cache目录 */public static String getDir(String name) {StringBuilder sb = new StringBuilder();if (isSDCardAvailable()) {sb.append(getExternalStoragePath());} else {sb.append(getCachePath());}sb.append(name);sb.append(File.separator);String path = sb.toString();if (createDirs(path)) {return path;} else {return null;}}/** 获取SD下的应用目录 */public static String getExternalStoragePath() {StringBuilder sb = new StringBuilder();sb.append(Environment.getExternalStorageDirectory().getAbsolutePath());sb.append(File.separator);sb.append(ROOT_DIR);sb.append(File.separator);return sb.toString();}/** 获取应用的cache目录 */public static String getCachePath() {File f = UIUtils.getContext().getCacheDir();if (null == f) {return null;} else {return f.getAbsolutePath() + "/";}}/** 创建文件夹 */public static boolean createDirs(String dirPath) {File file = new File(dirPath);if (!file.exists() || !file.isDirectory()) {return file.mkdirs();}return true;}/** 复制文件,可以选择是否删除源文件 */public static boolean copyFile(String srcPath, String destPath,boolean deleteSrc) {File srcFile = new File(srcPath);File destFile = new File(destPath);return copyFile(srcFile, destFile, deleteSrc);}/** 复制文件,可以选择是否删除源文件 */public static boolean copyFile(File srcFile, File destFile,boolean deleteSrc) {if (!srcFile.exists() || !srcFile.isFile()) {return false;}InputStream in = null;OutputStream out = null;try {in = new FileInputStream(srcFile);out = new FileOutputStream(destFile);byte[] buffer = new byte[1024];int i = -1;while ((i = in.read(buffer)) > 0) {out.write(buffer, 0, i);out.flush();}if (deleteSrc) {srcFile.delete();}} catch (Exception e) {LogUtils.e(e);return false;} finally {IOUtils.close(out);IOUtils.close(in);}return true;}/** 判断文件是否可写 */public static boolean isWriteable(String path) {try {if (StringUtils.isEmpty(path)) {return false;}File f = new File(path);return f.exists() && f.canWrite();} catch (Exception e) {LogUtils.e(e);return false;}}/** 修改文件的权限,例如"777"等 */public static void chmod(String path, String mode) {try {String command = "chmod " + mode + " " + path;Runtime runtime = Runtime.getRuntime();runtime.exec(command);} catch (Exception e) {LogUtils.e(e);}}/** * 把数据写入文件 * * @param is * 数据流 * @param path * 文件路径 * @param recreate * 如果文件存在,是否需要删除重建 * @return 是否写入成功 */public static boolean writeFile(InputStream is, String path,boolean recreate) {boolean res = false;File f = new File(path);FileOutputStream fos = null;try {if (recreate && f.exists()) {f.delete();}if (!f.exists() && null != is) {File parentFile = new File(f.getParent());parentFile.mkdirs();int count = -1;byte[] buffer = new byte[1024];fos = new FileOutputStream(f);while ((count = is.read(buffer)) != -1) {fos.write(buffer, 0, count);}res = true;}} catch (Exception e) {LogUtils.e(e);} finally {IOUtils.close(fos);IOUtils.close(is);}return res;}/** * 把字符串数据写入文件 * * @param content * 需要写入的字符串 * @param path * 文件路径名称 * @param append * 是否以添加的模式写入 * @return 是否写入成功 */public static boolean writeFile(byte[] content, String path, boolean append) {boolean res = false;File f = new File(path);RandomAccessFile raf = null;try {if (f.exists()) {if (!append) {f.delete();f.createNewFile();}} else {f.createNewFile();}if (f.canWrite()) {raf = new RandomAccessFile(f, "rw");raf.seek(raf.length());raf.write(content);res = true;}} catch (Exception e) {LogUtils.e(e);} finally {IOUtils.close(raf);}return res;}/** * 把字符串数据写入文件 * * @param content * 需要写入的字符串 * @param path * 文件路径名称 * @param append * 是否以添加的模式写入 * @return 是否写入成功 */public static boolean writeFile(String content, String path, boolean append) {return writeFile(content.getBytes(), path, append);}/** * 把键值对写入文件 * * @param filePath * 文件路径 * @param key * 键 * @param value * 值 * @param comment * 该键值对的注释 */public static void writeProperties(String filePath, String key,String value, String comment) {if (StringUtils.isEmpty(key) || StringUtils.isEmpty(filePath)) {return;}FileInputStream fis = null;FileOutputStream fos = null;File f = new File(filePath);try {if (!f.exists() || !f.isFile()) {f.createNewFile();}fis = new FileInputStream(f);Properties p = new Properties();p.load(fis);// 先读取文件,再把键值对追加到后面p.setProperty(key, value);fos = new FileOutputStream(f);p.store(fos, comment);} catch (Exception e) {LogUtils.e(e);} finally {IOUtils.close(fis);IOUtils.close(fos);}}/** 根据值读取 */public static String readProperties(String filePath, String key,String defaultValue) {if (StringUtils.isEmpty(key) || StringUtils.isEmpty(filePath)) {return null;}String value = null;FileInputStream fis = null;File f = new File(filePath);try {if (!f.exists() || !f.isFile()) {f.createNewFile();}fis = new FileInputStream(f);Properties p = new Properties();p.load(fis);value = p.getProperty(key, defaultValue);} catch (IOException e) {LogUtils.e(e);} finally {IOUtils.close(fis);}return value;}/** 把字符串键值对的map写入文件 */public static void writeMap(String filePath, Map<String, String> map,boolean append, String comment) {if (map == null || map.size() == 0 || StringUtils.isEmpty(filePath)) {return;}FileInputStream fis = null;FileOutputStream fos = null;File f = new File(filePath);try {if (!f.exists() || !f.isFile()) {f.createNewFile();}Properties p = new Properties();if (append) {fis = new FileInputStream(f);p.load(fis);// 先读取文件,再把键值对追加到后面}p.putAll(map);fos = new FileOutputStream(f);p.store(fos, comment);} catch (Exception e) {LogUtils.e(e);} finally {IOUtils.close(fis);IOUtils.close(fos);}}/** 把字符串键值对的文件读入map */@SuppressWarnings({ "rawtypes", "unchecked" })public static Map<String, String> readMap(String filePath,String defaultValue) {if (StringUtils.isEmpty(filePath)) {return null;}Map<String, String> map = null;FileInputStream fis = null;File f = new File(filePath);try {if (!f.exists() || !f.isFile()) {f.createNewFile();}fis = new FileInputStream(f);Properties p = new Properties();p.load(fis);map = new HashMap<String, String>((Map) p);// 因为properties继承了map,所以直接通过p来构造一个map} catch (Exception e) {LogUtils.e(e);} finally {IOUtils.close(fis);}return map;}/** 改名 */public static boolean copy(String src, String des, boolean delete) {File file = new File(src);if (!file.exists()) {return false;}File desFile = new File(des);FileInputStream in = null;FileOutputStream out = null;try {in = new FileInputStream(file);out = new FileOutputStream(desFile);byte[] buffer = new byte[1024];int count = -1;while ((count = in.read(buffer)) != -1) {out.write(buffer, 0, count);out.flush();}} catch (Exception e) {LogUtils.e(e);return false;} finally {IOUtils.close(in);IOUtils.close(out);}if (delete) {file.delete();}return true;}}
0 0
- 工具类
- 工具类!!!!
- 工具类
- 工具类
- 工具类
- 工具类
- 工具类
- 工具类
- 工具类
- 工具类
- 工具类
- 工具类
- 工具类
- 工具类
- 工具类
- 工具类
- 工具类
- 工具类
- mysql的c++封装类
- 循环链表
- Hive2.1.1安装
- 百度杯 二月场web-include By Assassin [文件包含漏洞]
- Mac下安装openCV
- 工具类
- java编译器:必须对其进行捕获或声明以便抛出
- 心酸的找工作之旅
- cocos2dx lua Listview
- CCF CSP 编程题目和解答-----试题名称:相邻数对-------201409-1
- Java内存模型与线程
- LeetCode #8 String to Integer (atoi)
- JavaWeb工程中web.xml基本配置
- Android的消息处理机制