1.屏幕相关
package com.example.coshenwancheng.utils;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.Window;
/**
* @desc: 屏幕相关
*/
public class DisplayUtils {
/**
* 是否横屏
*
* @param context
* @return
*/
public static boolean isLandscape(Context context) {
return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
}
/**
* 是否竖屏
*
* @param context
* @return
*/
public static boolean isPortrait(Context context) {
return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
}
/**
* Get screen width, in pixels
*
* @param context
* @return
*/
public static int getScreenWidth(Context context) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
return dm.widthPixels;
}
/**
* Get screen height, in pixels
*
* @param context
* @return
*/
public static int getScreenHeight(Context context) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
return dm.heightPixels;
}
/**
* Get screen density, the logical density of the display
*
* @param context
* @return
*/
public static float getScreenDensity(Context context) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
return dm.density;
}
/**
* Get screen density dpi, the screen density expressed as dots-per-inch
*
* @param context
* @return
*/
public static int getScreenDensityDPI(Context context) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
return dm.densityDpi;
}
/**
* Get bar height, this method cannot be used in onCreate(), (),onResume(), unless it is called in the
* post(Runnable).
*
* @param activity
* @return
*/
public static int get BarHeight(Activity activity) {
int statusBarHeight = getStatusBarHeight(activity);
int contentViewTop = activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
int BarHeight = contentViewTop - statusBarHeight;
return BarHeight < 0 ? 0 : BarHeight;
}
/**
* Get statusbar height, this method cannot be used in onCreate(), (),onResume(), unless it is called in the
* post(Runnable).
*
* @param activity
* @return
*/
public static int getStatusBarHeight(Activity activity) {
Rect rect = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplay (rect);
return rect.top;
}
/**
* Get statusbar height
*
* @param activity
* @return
*/
public static int getStatusBarHeight2(Activity activity) {
int statusBarHeight = getStatusBarHeight(activity);
if (0 == statusBarHeight) {
Class<?> localClass;
try {
localClass = Class.forName(\"com.android.internal.R$dimen\");
local = localClass.newInstance();
int id = Integer.parseInt(localClass.getField(\"status_bar_height\").get(local ).toString());
statusBarHeight = activity.getResources().getDimensionPixelSize(id);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
return statusBarHeight;
}
/**
* Convert dp to px by the density of phone
*
* @param context
* @param dp
* @return
*/
public static int dip2px(Context context, float dp) {
if (context == null) {
return -1;
}
return (int) (dipToPx(context, dp) + 0.5f);
}
/**
* Convert dp to px
*
* @param context
* @param dp
* @return
*/
private static float dipToPx(Context context, float dp) {
if (context == null) {
return -1;
}
float scale = context.getResources().getDisplayMetrics().density;
return dp * scale;
}
/**
* Convert px to dp by the density of phone
*
* @param context
* @param px
* @return
*/
public static int px2dip(Context context, float px) {
if (context == null) {
return -1;
}
return (int) (pxToDip(context, px) + 0.5f);
}
/**
* Convert px to dp
*
* @param context
* @param px
* @return
*/
private static float pxToDip(Context context, float px) {
if (context == null) {
return -1;
}
float scale = context.getResources().getDisplayMetrics().density;
return px / scale;
}
/**
* Convert px to sp
*
* @param context
* @param px
* @return
*/
public static int px2sp(Context context, float px) {
return (int) (pxToSp(context, px) + 0.5f);
}
/**
* Convert px to sp
*
* @param context
* @param px
* @return
*/
private static float pxToSp(Context context, float px) {
float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return px / fontScale;
}
/**
* Convert sp to px
*
* @param context
* @param sp
* @return
*/
public static int sp2px(Context context, float sp) {
return (int) (spToPx(context, sp) + 0.5f);
}
/**
* Convert sp to px
*
* @param context
* @param sp
* @return
*/
private static float spToPx(Context context, float sp) {
float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return sp * fontScale;
}
}
2获取文件大小的类
/*
* Copyright 2016 北京博瑞彤芸文化传播股份有限公司
*
* Licensed under the Apache License, Version 2.0 (the \"License\");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an \"AS IS\" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.example.coshenwancheng.utils;
import android.text.TextUtils;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
/**
* @de ion 获取文件大小的类
*/
public class FileSize {
public static final long SIZE_BT = 1024L;
public static final long SIZE_KB = SIZE_BT * 1024L;
public static final long SIZE_MB = SIZE_KB * 1024L;
public static final long SIZE_GB = SIZE_MB * 1024L;
public static final long SIZE_TB = SIZE_GB * 1024L;
public static final int SACLE = 2;
private File file;
private long longSize;
public FileSize(File file) {
this.file = file;
}
private void getFileSize() throws RuntimeException, IOException {
getFileSize(file);
}
private void getFileSize(File file) {
if (file == null || !file.exists()) {
return;
}
if (file.isFile()) {
this.longSize += file.length();
return;
}
File[] childArray = file.listFiles();
if (childArray == null || childArray.length == 0) {
return;
}
for (File child : childArray) {
getFileSize(child);
}
}
public String toString() throws RuntimeException {
try {
try {
getFileSize();
} catch (RuntimeException e) {
return \"\";
}
return convertSizeToString(this.longSize);
} catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex.getMessage());
}
}
/**
* 格式化输出文件大小
* @param fileSize
* @return
*/
public static String convertSizeToString(long fileSize) {
if (fileSize >= 0 && fileSize < SIZE_BT) {
return fileSize + \"B\";
} else if (fileSize >= SIZE_BT && fileSize < SIZE_KB) {
return fileSize / SIZE_BT + \"KB\";
} else if (fileSize >= SIZE_KB && fileSize < SIZE_MB) {
return fileSize / SIZE_KB + \"MB\";
} else if (fileSize >= SIZE_MB && fileSize < SIZE_GB) {
BigDecimal longs = new BigDecimal(Double.valueOf(fileSize + \"\").toString());
BigDecimal sizeMB = new BigDecimal(Double.valueOf(SIZE_MB + \"\").toString());
String result = longs.divide(sizeMB, SACLE, BigDecimal.ROUND_HALF_UP).toString();
// double result=this.longSize/(double)SIZE_MB;
return result + \"GB\";
} else {
BigDecimal longs = new BigDecimal(Double.valueOf(fileSize + \"\").toString());
BigDecimal sizeMB = new BigDecimal(Double.valueOf(SIZE_GB + \"\").toString());
String result = longs.divide(sizeMB, SACLE, BigDecimal.ROUND_HALF_UP).toString();
return result + \"TB\";
}
}
/**
* MB转KB
* @param fileSize
* @return
*/
public static double getKBSize(String fileSize) {
if (TextUtils.isEmpty(fileSize)) {
return 0;
}
fileSize = fileSize.toUpperCase();
int index;
if ((index = fileSize.indexOf(\"MB\")) > 0) {
String str = fileSize.substring(0, index).trim();
return string2double(str) * 1024;
}
if ((index = fileSize.indexOf(\"KB\")) > 0) {
String str = fileSize.substring(0, index).trim();
return string2double(str);
}
return 0;
}
public static double string2double(String doubleStr) {
try {
return Double.valueOf(doubleStr);
} catch (Exception e) {
}
return 0;
}
/**
* 获取文件的大小单位是byte
* @return 返回文件的大小
* @throws RuntimeException
*/
public long getLongSize() throws RuntimeException {
try {
getFileSize();
return longSize;
} catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex.getMessage());
}
}
}
3文件工具类
package com.example.coshenwancheng.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
/**
* @desc: 文件工具类
*/
public class FileUtils {
public final static String FILE_SUFFIX_SEPARATOR = \".\";
/**
* Read file
*
* @param filePath
* @param charsetName
* @return
*/
public static StringBuilder readFile(String filePath, String charsetName) {
File file = new File(filePath);
StringBuilder fileContent = new StringBuilder(\"\");
if (file == null || !file.isFile()) {
return null;
}
BufferedReader reader = null;
try {
InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);
reader = new BufferedReader(is);
String line = null;
while ((line = reader.readLine()) != null) {
if (!fileContent.toString().equals(\"\")) {
fileContent.append(\"\\r\\n\");
}
fileContent.append(line);
}
return fileContent;
} catch (IOException e) {
throw new RuntimeException(\"IOException\", e);
} finally {
IOUtils.close(reader);
}
}
/**
* Write file
*
* @param filePath
* @param content
* @param append
* @return
*/
public static boolean writeFile(String filePath, String content, boolean append) {
if (StringUtils.isEmpty(content)) {
return false;
}
FileWriter fileWriter = null;
try {
makeDirs(filePath);
fileWriter = new FileWriter(filePath, append);
fileWriter.write(content);
return true;
} catch (IOException e) {
throw new RuntimeException(\"IOException occurred. \", e);
} finally {
IOUtils.close(fileWriter);
}
}
/**
* write file, the string will be written to the begin of the file
*
* @param filePath
* @param content
* @return
*/
public static boolean writeFile(String filePath, String content) {
return writeFile(filePath, content, false);
}
/**
* Write file
*
* @param filePath
* @param is
* @return
*/
public static boolean writeFile(String filePath, InputStream is) {
return writeFile(filePath, is, false);
}
/**
* Write file
*
* @param filePath
* @param is
* @param append
* @return
*/
public static boolean writeFile(String filePath, InputStream is, boolean append) {
return writeFile(filePath != null ? new File(filePath) : null, is, append);
}
/**
* Write file
*
* @param file
* @param is
* @return
*/
public static boolean writeFile(File file, InputStream is) {
return writeFile(file, is, false);
}
/**
* Write file
*
* @param file
* @param is
* @param append
* @return
*/
public static boolean writeFile(File file, InputStream is, boolean append) {
OutputStream o = null;
try {
makeDirs(file.getAbsolutePath());
o = new FileOutputStream(file, append);
byte data[] = new byte[1024];
int length = -1;
while ((length = is.read(data)) != -1) {
o.write(data, 0, length);
}
o.flush();
return true;
} catch (FileNotFoundException e) {
throw new RuntimeException(\"FileNotFoundException\", e);
} catch (IOException e) {
throw new RuntimeException(\"IOException\", e);
} finally {
IOUtils.close(o);
IOUtils.close(is);
}
}
/**
* Move file
*
* @param srcFilePath
* @param destFilePath
*/
public static void moveFile(String srcFilePath, String destFilePath) throws FileNotFoundException {
if (StringUtils.isEmpty(srcFilePath) || StringUtils.isEmpty(destFilePath)) {
throw new RuntimeException(\"Both srcFilePath and destFilePath cannot be null.\");
}
moveFile(new File(srcFilePath), new File(destFilePath));
}
/**
* Move file
*
* @param srcFile
* @param destFile
*/
public static void moveFile(File srcFile, File destFile) throws FileNotFoundException {
boolean rename = srcFile.renameTo(destFile);
if (!rename) {
copyFile(srcFile.getAbsolutePath(), destFile.getAbsolutePath());
deleteFile(srcFile.getAbsolutePath());
}
}
/**
* Copy file
*
* @param srcFilePath
* @param destFilePath
* @return
* @throws FileNotFoundException
*/
public static boolean copyFile(String srcFilePath, String destFilePath) throws FileNotFoundException {
InputStream inputStream = new FileInputStream(srcFilePath);
return writeFile(destFilePath, inputStream);
}
/**
* rename file
*
* @param file
* @param newFileName
* @return
*/
public static boolean renameFile(File file, String newFileName) {
File newFile = null;
if (file.isDirectory()) {
newFile = new File(file.getParentFile(), newFileName);
} else {
String temp = newFileName
+ file.getName().substring(
file.getName().lastIndexOf(\'.\'));
newFile = new File(file.getParentFile(), temp);
}
if (file.renameTo(newFile)) {
return true;
}
return false;
}
/**
* Get file name without suffix
*
* @param filePath
* @return
*/
public static String getFileNameWithoutSuffix(String filePath) {
if (StringUtils.isEmpty(filePath)) {
return filePath;
}
int suffix = filePath.lastIndexOf(FILE_SUFFIX_SEPARATOR);
int fp = filePath.lastIndexOf(File.separator);
if (fp == -1) {
return (suffix == -1 ? filePath : filePath.substring(0, suffix));
}
if (suffix == -1) {
return filePath.substring(fp + 1);
}
return (fp < suffix ? filePath.substring(fp + 1, suffix) : filePath.substring(fp + 1));
}
/**
* Get file name
*
* @param filePath
* @return
*/
public static String getFileName(String filePath) {
if (StringUtils.isEmpty(filePath)) {
return filePath;
}
int fp = filePath.lastIndexOf(File.separator);
return (fp == -1) ? filePath : filePath.substring(fp + 1);
}
/**
* Get folder name
*
* @param filePath
* @return
*/
public static String getFolderName(String filePath) {
if (StringUtils.isEmpty(filePath)) {
return filePath;
}
int fp = filePath.lastIndexOf(File.separator);
return (fp == -1) ? \"\" : filePath.substring(0, fp);
}
/**
* Get suffix of file
*
* @param filePath
* @return
*/
public static String getFileSuffix(String filePath) {
if (StringUtils.isEmpty(filePath)) {
return filePath;
}
int suffix = filePath.lastIndexOf(FILE_SUFFIX_SEPARATOR);
int fp = filePath.lastIndexOf(File.separator);
if (suffix == -1) {
return \"\";
}
return (fp >= suffix) ? \"\" : filePath.substring(suffix + 1);
}
/**
* Create the directory
*
* @param filePath
* @return
*/
public static boolean makeDirs(String filePath) {
String folderName = getFolderName(filePath);
if (StringUtils.isEmpty(folderName)) {
return false;
}
File folder = new File(folderName);
return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();
}
/**
* Judge whether a file is exist
*
* @param filePath
* @return
*/
public static boolean isFileExist(String filePath) {
if (StringUtils.isEmpty(filePath)) {
return false;
}
File file = new File(filePath);
return (file.exists() && file.isFile());
}
/**
* Judge whether a folder is exist
*
* @param directoryPath
* @return
*/
public static boolean isFolderExist(String directoryPath) {
if (StringUtils.isEmpty(directoryPath)) {
return false;
}
File dire = new File(directoryPath);
return (dire.exists() && dire.isDirectory());
}
/**
* Delete file or folder
*
* @param path
* @return
*/
public static boolean deleteFile(String path) {
if (StringUtils.isEmpty(path)) {
return true;
}
File file = new File(path);
if (!file.exists()) {
return true;
}
if (file.isFile()) {
return file.delete();
}
if (!file.isDirectory()) {
return false;
}
if (file.isDirectory()) {
for (File f : file.listFiles()) {
if (f.isFile()) {
f.delete();
} else if (f.isDirectory()) {
deleteFile(f.getAbsolutePath());
}
}
}
return file.delete();
}
/**
* Delete file or folder
*
* @param file
* @return
*/
public static boolean deleteFile(File file) {
if (!file.exists()) {
return true;
}
if (file.isFile()) {
return file.delete();
}
if (!file.isDirectory()) {
return false;
}
if (file.isDirectory()) {
File[] childFile = file.listFiles();
if (childFile == null || childFile.length == 0) {
return file.delete();
}
for (File f : childFile) {
deleteFile(f);
}
}
return file.delete();
}
/**
* Get file size
*
* @param path
* @return
*/
public static long getFileSize(String path) {
if (StringUtils.isEmpty(path)) {
return -1;
}
File file = new File(path);
return (file.exists() && file.isFile() ? file.length() : -1);
}
/**
* Get folder size
*
* @param file
* @return
* @throws Exception
*/
public static long getFolderSize(File file) throws Exception {
long size = 0;
try {
File[] fileList = file.listFiles();
for (int i = 0; i < fileList.length; i++) {
if (fileList[i].isDirectory()) {
size = size + getFolderSize(fileList[i]);
} else {
size = size + fileList[i].length();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return size;
}
}
4Http请求的工具类
package com.example.coshenwancheng.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请求的工具类
*/
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()
{
@Override
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()
{
@Override
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;
}
}
5json的转换
package com.example.coshenwancheng.utils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @desc: json的转换
*/
public class JsonUtils {
/**
* Convert , list, ... to Json
* 转为json格式输出
* @param obj
* @return
*/
public static String toJson( obj) {
Gson gson = new Gson();
return gson.toJson(obj);
}
/**
* Convert a json string to
* 将json转为 对象
* @param json
* @param clazz
* @return
*/
public static <T> T jsonTo (String json, Class<T> clazz) {
Gson gson = new Gson();
return gson.fromJson(json, clazz);
}
/**
* Convert a json string to List<?>
* 将json转为list集合
* @param json
* @return
*/
public static <T> List<T> jsonToList(String json) {
Gson gson = new Gson();
return gson.fromJson(json, new TypeToken<List<T>>() {
}.getType());
}
/**
* Convert a json string to ArrayList<?>
* 将json转为ArrayList
* @param json
* @return
*/
public static <T> ArrayList<T> jsonToArrayList(String json) {
Gson gson = new Gson();
return gson.fromJson(json, new TypeToken<ArrayList<T>>() {
}.getType());
}
/**
* Convert a json string to Map<?, ?>
* 将json转为map
* @param json
* @return
*/
public static <K, V> Map<K, V> jsonToMap(String json) {
Gson gson = new Gson();
return gson.fromJson(json, new TypeToken<Map<K, V>>() {
}.getType());
}
/**
* Convert a json string to Generic<T>
* 将json转为泛型
* @param json
* @param <T>
* @return
*/
public static <T> T jsonToGeneric(String json, TypeToken<T> token) {
Gson gson = new Gson();
return gson.fromJson(json, token.getType());
}
}
6键盘工具类
/*
* Copyright 2015-2016 北京博瑞彤芸文化传播股份有限公司
*
* Licensed under the Apache License, Version 2.0 (the \"License\");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an \"AS IS\" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.coshenwancheng.utils;
import android.app.Activity;
import android.content.Context;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
/**
* @de ion 键盘工具类
*/
public class KeyboardUtil {
/**
* 隐藏键盘
*/
public static void hideSoftInput(Activity acitivity) {
InputMethodManager imm = (InputMethodManager) acitivity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(acitivity.getWindow().getDecorView().getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
/**
* 显示键盘
*/
public static void showSoftInput(EditText et) {
et.requestFocus();
InputMethodManager imm = (InputMethodManager) et.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(et, InputMethodManager.RESULT_UNCHANGED_SHOWN);
}
/**
* 展示键盘并选中最后一个
*/
public static void showSoftInputSelect(EditText et) {
showSoftInputSelect(et, 300);
}
/**
* 展示键盘并选中最后一个
*/
public static void showSoftInputSelect(final EditText et, long delayMillis) {
et.postDelayed(new Runnable() {
@Override
public void run() {
showSoftInput(et);
et.setSelection(et.getText().length());
}
}, delayMillis);
}
}
7Log统一管理类
package com.example.coshenwancheng.utils;
import android.util.Log;
/**
* Log统一管理类
*
*
*
*/
public class LogUtil
{
private LogUtil()
{
/* 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);
}
}
}
8MD5相关操作
package com.example.coshenwancheng.utils;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* @desc: MD5相关操作
*/
public class MD5Utils {
/**
* Encode MD5 for a string
*
* @param s
* @return
*/
public static String encodeMD5(String s) {
try {
MessageDigest digest = MessageDigest.getInstance(\"MD5\");
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
return toHexString(messageDigest);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return \"\";
}
private static String toHexString(byte[] keyData) {
if (keyData == null) {
return null;
}
int expectedStringLen = keyData.length * 2;
StringBuilder sb = new StringBuilder(expectedStringLen);
for (int i = 0; i < keyData.length; i++) {
String hexStr = Integer.toString(keyData[i] & 0x00FF, 16);
if (hexStr.length() == 1) {
hexStr = \"0\" + hexStr;
}
sb.append(hexStr);
}
return sb.toString();
}
/**
* Encode MD5 for a string
*
* @param s
* @return
*/
public final static String encodeMD52(String s) {
char hexDigits[] = {\'0\', \'1\', \'2\', \'3\', \'4\', \'5\', \'6\', \'7\', \'8\', \'9\', \'a\', \'b\', \'c\', \'d\', \'e\', \'f\'};
try {
byte[] btInput = s.getBytes();
MessageDigest digest = MessageDigest.getInstance(\"MD5\");
digest.update(btInput);
byte[] md = digest.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Encode md5 for a single file
*
* @param f
* @return
*/
public static String encodeMD5(File f) {
if (!f.isFile()) {
return null;
}
MessageDigest digest = null;
byte buffer[] = new byte[1024];
int len;
try {
digest = MessageDigest.getInstance(\"MD5\");
FileInputStream in = new FileInputStream(f);
while ((len = in.read(buffer, 0, 1024)) != -1) {
digest.update(buffer, 0, len);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(16);
}
}
9跟网络相关的工具类
package com.example.coshenwancheng.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数字格式化操作类
package com.example.coshenwancheng.utils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
/**
* @desc: 数字格式化操作类
*/
public class NumberUtils {
/**
* 保留一位小数
*
* @param number
* @return
*/
public static String formatOneDecimal(float number) {
DecimalFormat oneDec = new DecimalFormat(\"##0.0\");
return oneDec.format(number);
}
/**
* 保留两位小数
*
* @param number
* @return
*/
public static String formatTwoDecimal(float number) {
DecimalFormat twoDec = new DecimalFormat(\"##0.00\");
return twoDec.format(number);
}
/**
* 保留两位小数百分比
*
* @param number
* @return
*/
public static String formatTwoDecimalPercent(float number) {
return formatTwoDecimal(number) + \"%\";
}
/**
* 四舍五入
*
* @param number
* @param scale scale of the result returned.
* @return
*/
public static double roundingNumber(float number, int scale) {
return roundingNumber(number, scale, RoundingMode.HALF_UP);
}
/**
* 四舍五入
*
* @param number
* @param scale scale of the result returned.
* @param roundingMode rounding mode to be used to round the result.
* @return
*/
public static double roundingNumber(float number, int scale, RoundingMode roundingMode) {
BigDecimal b = new BigDecimal(number);
return b.setScale(scale, roundingMode).doubleValue();
}
}
继续阅读与本文标签相同的文章
下一篇 :
年薪百万的机器学习专家,为什么不产生价值?
-
88%中国员工相信AI超过经理 人见多了就更喜欢狗?
2026-05-18栏目: 教程
-
删库不要跑,我站起来还可以删
2026-05-18栏目: 教程
-
拼硬件真过时了?卡萨帝冰箱乌镇全讲场景
2026-05-18栏目: 教程
-
哈弗F7有AI更便捷 全球最流行的交互方式了解一下
2026-05-18栏目: 教程
-
浙江移动成今年世界互联网大会高级合作伙伴
2026-05-18栏目: 教程
