/**
* 获取屏幕的宽高
*
* @param con
* @return
*/
public static int[] getScreenParams(Context con) {
WindowManager manager = ((Activity) con).getWindowManager();
return new int[] { manager.getDefaultDisplay().getWidth(),
manager.getDefaultDisplay().getHeight() };
}
/**
* 重置图片大小
*
* @param c
*/
public static Bitmap resizeBitmap(Context c, String path) {
int windowWidth = ((Activity) c).getWindowManager().getDefaultDisplay()
.getWidth();
int windowHeight = ((Activity) c).getWindowManager()
.getDefaultDisplay().getHeight();
// 图片解析的配置
BitmapFactory.Options options = new Options();
// 不去真的解析图片,只是获取图片的头部信息宽,高
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
// 计算缩放比例
int scaleX = imageWidth / windowWidth;
int scaleY = imageHeight / windowHeight;
int scale = 1;
if (scaleX > scaleY & scaleY >= 1) {
scale = scaleX;
} else if (scaleY > scaleX & scaleX >= 1) {
scale = scaleY;
}
// 真的解析图片
options.inJustDecodeBounds = false;
// 设置采样率
options.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFile(path, options);
return bitmap;
}
/**
* 半角转换为全角
*
* @param input
* @return ddddddd
*/
public static String ToDBC(String input) {
char[] c = input.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == 12288) {
c[i] = (char) 32;
continue;
}
if (c[i] > 65280 && c[i] < 65375)
c[i] = (char) (c[i] - 65248);
}
return new String(c);
}
public static String object2String(Object obj) {
String result = "";
if (obj != null) {
result = String.valueOf(obj);
}
return result;
}
/**
* 字符串转换成int
*
* @param str
* 字符串参数
* @return
*/
public static int String2int(String str) {
if (str != null && !str.equals("")) {
return Integer.parseInt(str);
}
return -1;
}
/**
* 解析json数据插入数据库
*
* @param context
*
*/
public static String readData(Context context, int id) {
InputStream in = context.getResources().openRawResource(id);
// 将in读入reader 中
BufferedReader br;
try {
br = new BufferedReader(new InputStreamReader(in, "GBK"));
StringBuffer buffer = new StringBuffer("");
String tem = "";
while ((tem = br.readLine()) != null) {
buffer.append(tem);
}
br.close();
return buffer.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 检查当前手机网络
*
* @param context
* @return
*/
public static boolean isNetConnected(Context context) {
// 判断连接方式
boolean wifiConnected = isWifiConnected(context);
boolean mobileConnected = isMobileConnected(context);
if (wifiConnected == false && mobileConnected == false) {
// 如果都没有连接返回false,提示用户当前没有网络
return false;
}
return true;
}
// 判断手机使用是wifi还是mobile
/**
* 判断手机是否采用wifi连接
*/
public static boolean isWifiConnected(Context context) {
// Context.CONNECTIVITY_SERVICE).
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
/**
* 手机移动网络是否连接
*
* @param context
* @return
*/
public static boolean isMobileConnected(Context context) {
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
/**
* 显示Toast提示框
*
* @param context
* @param msg
* 提示内容
*/
public static void showToast(Context context, String msg) {
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
/**
* 显示Toast提示框
*
* @param context
* @param stringId
* stringid
*/
public static void showToast(Context context, int stringId) {
Toast.makeText(context, context.getString(stringId), Toast.LENGTH_SHORT)
.show();
}
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
/**
* 获取当前时间
*
* @param pattern
* @return
*/
public static String getCurrentDate(String pattern) {
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
return dateFormat.format(new Date());
}
/**
* 格式化时间字符串
*
* @return String
*/
public static String formatDate(Date date) {
if (date == null)
date = new Date();
String code = new String();
SimpleDateFormat matter = new SimpleDateFormat("MM月dd日 HH:mm");
code = matter.format(date);
return code;
}
/**
* 测试是否是Email地址
*
* @param email地址
* @return 测试结果
*/
public static boolean testEmail(String email) {
String regex = "^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\\.([a-zA-Z0-9_-])+)+$";
return email.matches(regex);
}
/**
* JSON字符串去掉最外层[]
*
* @param str
* @return
*/
public static String deleteMark(String str) {
int start = str.indexOf("[");
if (start == 0) {
int end = str.lastIndexOf("]");
return str.substring(start + 1, end);
}
return str;
}
/**
* 利用反射给对象赋值
*
* @param obj
* @param cursor
*/
public static void setClassValueBycursor(Object obj, Cursor cursor) {
int ColCount = cursor.getColumnCount();
int i = 0;
for (i = 0; i < ColCount; i++) {
String ColName = cursor.getColumnName(i);
try {
Field f = obj.getClass().getField(ColName);
String ret = cursor.getString(i);
if (f == null)
continue;
if (ret == null)
ret = "";
f.set(obj, ret);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 进入画面时,关闭键盘
*
* @param context
*/
public static void closeWhenOncreate(Context context) {
// SOFT_INPUT_STATE_ALWAYS_VISIBLE 键盘始终显示
((Activity) context).getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
/**
*
* @param context
* view所在activity
* @param view
* 当前activity中获取焦点的view
*/
public static void closeKeyboardForCommonAct(Context context, View view) {
InputMethodManager imm = (InputMethodManager) ((Activity) context)
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (((Activity) context).getCurrentFocus().getWindowToken() != null) {
imm.hideSoftInputFromInputMethod(view.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
/**
* 普通关闭
*
* @param context
*/
public static void closeKeyboardCommAct(Context context) {
InputMethodManager imm = (InputMethodManager) ((Activity) context)
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (((Activity) context).getCurrentFocus() != null) {
imm.hideSoftInputFromWindow(((Activity) context).getCurrentFocus()
.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
/**
* 全角转换成半角,适应屏幕:TextView换行时,全角和半角导致显示混乱。 /全角空格为12288,半角空格为32 /其他字符半角(33
* -126)与全角(65281- 65374)的对应关系是:均相差65248
*
* @param input
* @return
*/
public static String changeQuanj2Banj(String input) {
char[] c = input.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == 12288) {
c[i] = (char) 32;
}
if (c[i] > 65280 && c[i] < 65375) {
c[i] = (char) (c[i] - 65248);
}
}
return String.valueOf(c);
}
/**
* 检查sd卡是否可用
*
* @return
*/
public static boolean checkSDCardAvaliable() {
if (Environment.getExternalStorageState() == Environment.MEDIA_REMOVED) {
return false;
}
return true;
}
/**
* 检查是否为数字,包括含小数点的
*
* @param str
* @return
*/
public static boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("(([+\\-])?(\\d+)?)?(\\.(\\d+)?)?$");// (([+\\-])?(\\d+)?)?(\\.(\\d+)?)?$
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
}
return true;
}
/**
* 检查指定服务是否在运行
*
* @param context
* @param serviceName
* @return
*/
public static boolean IsServiceRunning(Context context, String serviceName) {
ActivityManager activityManage = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> serviceList = activityManage
.getRunningServices(30);
for (ActivityManager.RunningServiceInfo info : serviceList) {
if (info.service.getClassName().equals(serviceName)) {
return true;
} else {
continue;
}
}
return false;
}
/**
* 按照特定尺寸计算图片缩放值。倍数
*
* @param options
* @param reqWidth
* @param reqHeight
* @return
*/
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// 原始图片的宽高
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// 在保证解析出的bitmap宽高分别大于目标尺寸宽高的前提下,取可能的inSampleSize的最大值
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
/**
* 根据resid获取图片
*
* @param res
* @param resId
* @param reqWidth
* @param reqHeight
* @return
*/
public static Bitmap decodeSampledBitmapFromResource(Resources res,
int resId, int reqWidth, int reqHeight) {
// 首先设置 inJustDecodeBounds=true 来获取图片尺寸
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// 计算 inSampleSize 的值
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// 根据计算出的 inSampleSize 来解码图片生成Bitmap
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
/**
* 对文件操作的工具类。
* @author
*
*/
public class FileUtil {
/**
* 获取文件名称
*
* @param str
* @return
*/
public static String getFileName(String str) {
// 去除url中的符号作为文件名返回
str = str.replaceAll("(?i)[^a-zA-Z0-9\u4E00-\u9FA5]", "");
System.out.println("filename = " + str);
return str + ".png";
}
/**
* 将文件保存至sd卡
*
* @param fileName
* @param inputStream
*/
public static void writeSDcard(String fileName, InputStream inputStream) {
try {
File file = new File(Constants.DOWNLOAD_PATH);
if (!file.exists()) {
file.mkdirs();
}
FileOutputStream fileOutputStream = new FileOutputStream(
Constants.DOWNLOAD_PATH + fileName);
byte[] buffer = new byte[512];
int count = 0;
while ((count = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, count);
}
fileOutputStream.flush();
fileOutputStream.close();
inputStream.close();
System.out.println("writeToSD success");
} catch (IOException e) {
e.printStackTrace();
System.out.println("writeToSD fail");
}
}
/**
* 将文件保存到sd卡
*
* @param fileName
* 文件完整路径
* @param inputStream
* @return
*/
public static boolean writeFile2SDcard(String fileName,
InputStream inputStream) {
try {
if (null == inputStream) {
return false;
}
File file = new File(Constants.DOWNLOAD_PATH);
if (!file.exists()) {
file.mkdirs();
}
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
byte[] buffer = new byte[1024];
int count = 0;
while ((count = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, count);
}
fileOutputStream.flush();
fileOutputStream.close();
inputStream.close();
System.out.println("writeToSD success");
return true;
} catch (IOException e) {
e.printStackTrace();
System.out.println("writeToSD fail");
return false;
}
}
/**
* 保存图片到sd卡
*
* @param fileName 文件名称
* @param bmp 对应的图片Bitmap
* @return
*/
public static boolean writeBitmap2SDcard(String fileName, Bitmap bmp) {
try {
File file = new File(Constants.DOWNLOAD_PATH);
if (!file.exists()) {
//判断是否存在下载目录
file.mkdirs();
}
InputStream is = bitmap2InputStream(bmp);
File imgFile = new File(Constants.DOWNLOAD_PATH
+ getFileName(fileName));
if (!imgFile.exists()) {
imgFile.createNewFile();
}
FileOutputStream fileOutputStream = new FileOutputStream(imgFile);
byte[] buffer = new byte[512];
int count = 0;
while ((count = is.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, count);
}
fileOutputStream.flush();
fileOutputStream.close();
is.close();
System.out.println("writeToSD success");
} catch (IOException e) {
e.printStackTrace();
System.out.println("writeToSD fail");
return false;
}
return true;
}
/**
* // Bitmap转换成byte[]
*
* @param bm 目标Bitmap
* @return
*/
public static byte[] bitmap2Bytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
/**
* // 将Bitmap转换成InputStream
*
* @param bm
* @return
*/
public static InputStream bitmap2InputStream(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
InputStream is = new ByteArrayInputStream(baos.toByteArray());
return is;
}
/**
* 将输入流转换成字节数组
* @param is 输入流
* @return
*/
public static byte[] changeIs2ByteArr(InputStream is) {
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int len = -1;
byte b[] = new byte[2048];
while ((len = is.read(b)) != -1) {
byteArrayOutputStream.write(b, 0, len);
}
return byteArrayOutputStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 查看文件是否存在
*
* @param path 文件路径
* @return
*/
public static boolean isFileExist(String path) {
File file = new File(path);
if (file.exists()) {
return true;
}
return false;
}
/**
* 格式化文件大
*
* @param volume
* 文件大小
* @return 格式化的字符
*/
public static String getVolume(long volume) {
float num = 1.0F;
String str = null;
if (volume < 1024) {
str = volume + "B";
} else if (volume < 1048576) {
num = num * volume / 1024;
str = String.format("%.1f", num) + "K";
} else if (volume < 1073741824) {
num = num * volume / 1048576;
str = String.format("%.1f", num) + "M";
} else if (volume < 1099511627776L) {
num = num * volume / 1073741824;
str = String.format("%.1f", num) + "G";
}
return str;
}
/**
*
* <p>
* 网网络下载文件(图片,附件,视频等)
* </p>
*
*
*/
public class HttpDownloadFile {
/**
* 获取文件输入流
*
* @param httpUrl 网络路径
* @return
*/
public static InputStream getInputstream(String httpUrl) {
URL url = null;
InputStream is = null;
try {
url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setConnectTimeout(5 * 1000);
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
/**
* 网络获取图片
*
* @param url 图片的网络路径
* @return
*/
public static Bitmap httpGetBmp(String url) {
HttpGet httpget = new HttpGet(url);
BasicHttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
Bitmap bitmap = null;
try {
HttpClient httpclient = new DefaultHttpClient(httpParams);
HttpResponse response = httpclient.execute(httpget);
InputStream is = response.getEntity().getContent();
byte[] bytes = new byte[1024];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int count = 0;
while ((count = is.read(bytes)) != -1) {
System.out.println("readBitmap");
bos.write(bytes, 0, count);
}
byte[] byteArray = bos.toByteArray();
bitmap = BitmapFactory.decodeByteArray(byteArray, 0,
byteArray.length);
is.close();
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}