import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by kangzhiwei on 2019-11-01.
* 公共方法工具类
*/
public class CommonUtils {
public static final int NETTYPE_WIFI = 0x01;
public static final int NETTYPE_CMWAP = 0x02;
public static final int NETTYPE_CMNET = 0x03;
/**
* 获取应用程序名称
*/
public static String getAppName(Context context) {
try {
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(
context.getPackageName(), 0);
int labelRes = packageInfo.applicationInfo.labelRes;
return context.getResources().getString(labelRes);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
/**
* [获取应用程序版本名称信息]
*
* @param context
* @return 当前应用的版本名称
*/
public static String getVersionName(Context context) {
try {
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(
context.getPackageName(), 0);
return packageInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
/**
* 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
*
* @param context
* @param pxValue
* @return
*/
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
/**
* 关闭软键盘
*
* @param mEditText 输入框
* @param mContext 上下文
*/
public static void closeKeybord(EditText mEditText, Context mContext) {
InputMethodManager imm = (InputMethodManager) mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
}
/**
* md5加密方法
*
* @param password
* @return
*/
public static String md5Password(String password) {
try {
// 得到一个信息摘要器
MessageDigest digest = MessageDigest.getInstance("md5");
byte[] result = digest.digest(password.getBytes());
StringBuffer buffer = new StringBuffer();
// 把没一个byte 做一个与运算 0xff;
for (byte b : result) {
// 与运算
int number = b & 0xff;// 加盐
String str = Integer.toHexString(number);
// System.out.println(str);
if (str.length() == 1) {
buffer.append("0");
}
buffer.append(str);
}
// 标准的md5加密后的结果
return buffer.toString();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
/**
* 获得屏幕高度
*
* @param context
* @return
*/
public static int getScreenWidth(Context context) {
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.widthPixels;
}
/**
* 获得屏幕宽度
*
* @param context
* @return
*/
public static int getScreenHeight(Context context) {
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.heightPixels;
}
/**
* 获得状态栏的高度
*
* @param context
* @return
*/
public static int getStatusHeight(Context context) {
int statusHeight = -1;
try {
Class<?> clazz = Class.forName("com.android.internal.R$dimen");
Object object = clazz.newInstance();
int height = Integer.parseInt(clazz.getField("status_bar_height")
.get(object).toString());
statusHeight = context.getResources().getDimensionPixelSize(height);
} catch (Exception e) {
e.printStackTrace();
}
return statusHeight;
}
/**
* 获取当前屏幕截图,包含状态栏
*
* @param activity
* @return
*/
public static Bitmap snapShotWithStatusBar(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
int width = getScreenWidth(activity);
int height = getScreenHeight(activity);
Bitmap bp = null;
bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
view.destroyDrawingCache();
return bp;
}
/**
* 获取当前屏幕截图,不包含状态栏
*
* @param activity
* @return
*/
public static Bitmap snapShotWithoutStatusBar(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
int width = getScreenWidth(activity);
int height = getScreenHeight(activity);
Bitmap bp = null;
bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height
- statusBarHeight);
view.destroyDrawingCache();
return bp;
}
/**
* 判断SDCard是否可用
*
* @return
*/
public static boolean isSDCardEnable() {
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
/**
* 获取SD卡路径
*
* @return
*/
public static String getSDCardPath() {
return Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator;
}
/**
* 获取SD卡的剩余容量 单位byte
*
* @return
*/
public static long getSDCardAllSize() {
if (isSDCardEnable()) {
StatFs stat = new StatFs(getSDCardPath());
// 获取空闲的数据块的数量
long availableBlocks = stat.getAvailableBlocks();
// 获取单个数据块的大小(byte)
long blockSize = stat.getBlockSize();
return blockSize * availableBlocks;
}
return 0;
}
/**
* 获取指定路径所在空间的剩余可用容量字节数,单位byte
*
* @param filePath
* @return 容量字节 SDCard可用空间,内部存储可用空间
*/
public static long getFreeBytes(String filePath) {
// 如果是sd卡的下的路径,则获取sd卡可用容量
if (filePath.startsWith(getSDCardPath())) {
filePath = getSDCardPath();
} else {// 如果是内部存储的路径,则获取内存存储的可用容量
filePath = Environment.getDataDirectory().getAbsolutePath();
}
StatFs stat = new StatFs(filePath);
long availableBlocks = (long) stat.getAvailableBlocks() - 4;
return stat.getBlockSize() * availableBlocks;
}
/**
* 获取系统存储路径
*
* @return
*/
public static String getRootDirectoryPath() {
return Environment.getRootDirectory().getAbsolutePath();
}
/**
* 设置屏幕亮度
*
* @param activity
* @param brightness 屏幕亮度值
*/
public static void changeAppBrightness(Activity activity, int brightness) {
Window window = activity.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
if (brightness == -1) {
lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
} else {
lp.screenBrightness = (brightness <= 0 ? 1 : brightness) / 255f;
}
window.setAttributes(lp);
}
/**
* 恢复屏幕亮度到系统亮度
*
* @param activity
* @return
*/
public static int getSystemBrightness(Activity activity) {
int systemBrightness = 0;
try {
systemBrightness = Settings.System.getInt(activity.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
return systemBrightness;
}
/**
* 字符串是否为空
*
* @param str
* @return
*/
public static boolean isEmpty(String str) {
if (str == null || "".equals(str) || "null".equalsIgnoreCase(str)) {
return true;
}
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
return false;
}
}
return true;
}
/**
* 字符串转换成为16进制(无需Unicode编码)
*
* @param str
* @return
*/
public static String str2HexStr(String str) {
if (isEmpty(str)) {
str = "null";
}
char[] chars = "0123456789ABCDEF".toCharArray();
StringBuilder sb = new StringBuilder("");
byte[] bs = str.getBytes();
int bit;
for (int i = 0; i < bs.length; i++) {
bit = (bs[i] & 0x0f0) >> 4;
sb.append(chars[bit]);
bit = bs[i] & 0x0f;
sb.append(chars[bit]);
}
return sb.toString().trim();
}
/**
* 图片转化为16进制
*
* @param imgPath
* @return
*/
public static String convertImgToHexString(String imgPath) {
Log.d("lll", "convertImgToHexString: path " + imgPath);
try {
StringBuffer sb = new StringBuffer();
FileInputStream fis = new FileInputStream(imgPath);
BufferedInputStream bis = new BufferedInputStream(fis);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len = 0;
while ((len = fis.read(buff)) != -1) {
bos.write(buff, 0, len);
}
// 得到图片的字节数组
byte[] result = bos.toByteArray();
Log.d("lll", "convertImgToHexString: 数组转string");
return byte2hex(result);
// return result.toString();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
/**
* 二进制转字符串
*
* @param b
* @return
*/
public static String byte2hex(byte[] b) {
StringBuilder sb = new StringBuilder();
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0XFF);
if (stmp.length() == 1) {
sb.append("0" + stmp);
} else {
sb.append(stmp);
}
}
Log.d("lll", "convertImgToHexString: 图片16进制处理完成");
return sb.toString();
}
/**
* 正常toast
*
* @param context
* @param msg
*/
public static void toast(Context context, String msg) {
if (isEmpty(msg)) {
return;
}
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
/**
* 屏幕中间toast
*
* @param context
* @param msg
*/
public static void secterToast(Context context, String msg) {
if (isEmpty(msg)) {
return;
}
Toast toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
/**
* 保留小数位。
*
* @param value 需要处理的数
* @param digits 保留几位
* @return 保留后的字符串
*/
public static String setup(double value, int digits) {
StringBuffer b = new StringBuffer();
for (int i = 0; i < digits; i++) {
if (i == 0) {
b.append(".");
}
b.append("0");
}
DecimalFormat format = new DecimalFormat("###,###,###,##0" + b.toString());
return format.format(value);
}
/**
* 是否含有中文
*/
public static boolean isContainChinese(String str) {
Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
Matcher m = p.matcher(str);
if (m.find()) {
return true;
}
return false;
}
/**
* 拨打电话
*
* @param context
* @param phone
*/
public static void callPhone(Context context, String phone) {
Intent dialIntent = new Intent(Intent.ACTION_DIAL);
dialIntent.setData(Uri.parse("tel:" + phone));
context.startActivity(dialIntent);
}
/**
* 是否为手机号
* \\d代表0-9 {10} 代表有10个数字
*
* @param number
* @return
*/
public static boolean validMobile(String number) {
return number != null && number.matches("1\\d{10}");
}
/**
* 判定邮箱
*
* @param email
* @return
*/
public static boolean isEmailAddress(String email) {
if (email == null) {
return false;
}
String regex = "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" + "\\@"
+ "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + "(" + "\\."
+ "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" + ")+";
return email.matches(regex);
}
/**
* 获取当前网络类型
*
* @param context
* @return 0:没有网络 1:WIFI网络 2:WAP网络 3:NET网络
*/
public static int getNetworkType(Context context) {
int netType = 0;
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo == null) {
return netType;
}
int nType = networkInfo.getType();
if (nType == ConnectivityManager.TYPE_MOBILE) {
String extraInfo = networkInfo.getExtraInfo();
if (!TextUtils.isEmpty(extraInfo)) {
if (extraInfo.toLowerCase().equals("cmnet")) {
netType = NETTYPE_CMNET;
} else {
netType = NETTYPE_CMWAP;
}
}
} else if (nType == ConnectivityManager.TYPE_WIFI) {
netType = NETTYPE_WIFI;
}
return netType;
}
/**
* 获取assets文件中的bitmap
* @param context
* @param path
* @return
*/
public static Bitmap readBitmapFromAssets(Context context, String path) {
Bitmap bmp = null;
try {
InputStream is = context.getAssets().open(path);
bmp = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return bmp;
}
/**
* 判断GPS是否开启,GPS或者AGPS开启一个就认为是开启的
*
* @param context
* @return true 表示开启
*/
public static boolean isGpsOPen(final Context context) {
LocationManager locationManager
= (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// 通过GPS卫星定位,定位级别可以精确到街(通过24颗卫星定位,在室外和空旷的地方定位准确、速度快)
boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// 通过WLAN或移动网络(3G/2G)确定的位置(也称作AGPS,辅助GPS定位。主要用于在室内或遮盖物(建筑群或茂密的深林等)密集的地方定位)
boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
return gps || network;
}
/** 根据包名启动应用
* @param context
* @param packagename
*/
public static void doStartApplicationWithPackageName(Context context, String packagename) {
// 通过包名获取此APP详细信息,包括Activities、services、versioncode、name等等
PackageInfo packageinfo = null;
try {
packageinfo = context.getPackageManager().getPackageInfo(packagename, 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
if (packageinfo == null) {
return;
}
// 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
resolveIntent.setPackage(packageinfo.packageName);
// 通过getPackageManager()的queryIntentActivities方法遍历
List<ResolveInfo> resolveinfoList = context.getPackageManager()
.queryIntentActivities(resolveIntent, 0);
ResolveInfo resolveinfo = resolveinfoList.iterator().next();
if (resolveinfo != null) {
// packagename = 参数packname
String packageName = resolveinfo.activityInfo.packageName;
// 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式:packagename.mainActivityname]
String className = resolveinfo.activityInfo.name;
// LAUNCHER Intent
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
// 设置ComponentName参数1:packagename参数2:MainActivity路径
ComponentName cn = new ComponentName(packageName, className);
intent.setComponent(cn);
context.startActivity(intent);
}
}
/**
* 使用系统播放器播放视频
*
* @param context
* @param mediaUrl
*/
public static void playMedia(final Context context, final String mediaUrl) {
if (!isNetAvailable(context)) {
Toast.makeText(context, "您的网络异常,视频暂时无法播放", Toast.LENGTH_SHORT).show();
return;
}
int type = getNetworkType(context);
if (type != 1 && type != 0) {
new AlertDialog.Builder(context)
.setMessage("您当前处于非WiFi状态,观看视频可能会消耗大量网络数据")
.setNegativeButton("继续观看", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(mediaUrl), "video/*");
context.startActivity(intent);
}
})
.setPositiveButton("返回", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
} else if (type == 1) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(mediaUrl), "video/*");
context.startActivity(intent);
}
}
public static boolean isNetAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnectedOrConnecting();
}
}