import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
/**
* 简单的工具类
*/
public class AndroidUtil {
/**
* 获取应用版本名
*
* @param context
* @return
*/
public static String getVersionName(Context context) {
PackageManager packageManager = context.getPackageManager();
try {
PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return "";
}
/**
* 获取应用版本号
*
* @param context
* @return
*/
public static int getVersionCode(Context context) {
PackageManager packageManager = context.getPackageManager();
try {
PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return 0;
}
/**
* 根据包名判断app是否已安装
*
* @param context
* @param packageName
* @return
*/
private static boolean isAppInstalled(Context context, String packageName) {
try {
final PackageManager packageManager = context.getPackageManager();
List<PackageInfo> infoList = packageManager.getInstalledPackages(0);
List<String> pName = new ArrayList<>();
if (infoList != null) {
for (int i = 0; i < infoList.size(); i++) {
String pn = infoList.get(i).packageName;
pName.add(pn);
}
}
return pName.contains(packageName);
} catch (Exception ex) {
return false;
}
}
/**
* 根据包名,在Google应用商店找到指定应用
*
* @param context
* @param packageName
*/
public static void findAppFromGooglePlay(Context context, String packageName) {
if (isAppInstalled(context, "com.android.vending")) {
// 已安裝GooglePlay,跳原生
try {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/details?id=" + packageName));
intent.setClassName("com.android.vending",
"com.google.android.finsky.activities.MainActivity");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} catch (Exception ex) {
}
}
}
/**
* 返回到桌面
*
* @param context
*/
public static void startHomeActivity(Context context) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
context.startActivity(intent);
}
/**
* 判断app是否运行在后台
*
* @param context
* @return
*/
public static boolean isAppRunInBackground(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
if (list != null && list.size() > 0) {
ComponentName cn = list.get(0).topActivity;
if (!cn.getPackageName().equals(context.getPackageName())) {
return true;
}
}
return false;
}
/**
* 判断app是否运行在前台
*
* @param context
* @return
*/
private boolean isAppRunInForeground(Context context) {
try {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
if (list != null && list.size() > 0) {
ComponentName cn = list.get(0).topActivity;
if (cn.getPackageName().equals(context.getPackageName())) {
return true;
}
}
} catch (Exception ex) {
}
return false;
}
/**
* 打开系统设置界面
*
* @param context
*/
public static void launchSystemSettings(Context context) {
Intent mIntent = new Intent();
ComponentName comp = new ComponentName("com.android.settings", "com.android.settings.Settings");
mIntent.setComponent(comp);
mIntent.setAction(Intent.ACTION_VIEW);
context.startActivity(mIntent);
}
/**
* 打开app设置界面
*
* @param context
*/
public static void launchAppSettings(Context context) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.fromParts("package", context.getPackageName(), null));
context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
/**
* 获取app的SHA1值
*
* @param context
* @return
*/
public static String getAppSignatureSHA1(Context context) {
return getAppSignatureHash(context, "SHA1");
}
/**
* 获取app的SHA256值
*
* @param context
* @return
*/
public static String getAppSignatureSHA256(Context context) {
return getAppSignatureHash(context, "SHA256");
}
/**
* 获取app的MD5值
*
* @param context
* @return
*/
public static String getAppSignatureMD5(Context context) {
return getAppSignatureHash(context, "MD5");
}
private static String getAppSignatureHash(Context context, final String algorithm) {
Signature[] signature;
try {
PackageManager pm = context.getPackageManager();
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
signature = pi.signatures;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return null;
}
if (signature != null && signature.length > 0) {
try {
byte[] data = signature[0].toByteArray();
MessageDigest md = MessageDigest.getInstance(algorithm);
md.update(data);
data = md.digest();
if (data != null && data.length > 0) {
int len = data.length;
if (len <= 0) return "";
char[] ret = new char[len << 1];
char HEX_DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
for (int i = 0, j = 0; i < len; i++) {
ret[j++] = HEX_DIGITS[data[i] >> 4 & 0x0f];
ret[j++] = HEX_DIGITS[data[i] & 0x0f];
}
return new String(ret).replaceAll("(?<=[0-9A-F]{2})[0-9A-F]{2}", ":$0");
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
return "";
}
/**
* 获取状态栏高度
*
* @param context
* @return
*/
public static int getStatusHeight(Context context) {
int statusHeight = -1;
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId <= 0) {
try {
Class<?> clazz = Class.forName("com.android.internal.R$dimen");
Object object = clazz.newInstance();
resourceId = Integer.parseInt(clazz.getField("status_bar_height").get(object).toString());
} catch (Exception e) {
e.printStackTrace();
}
}
if (resourceId > 0) {
statusHeight = context.getResources().getDimensionPixelSize(resourceId);
}
if (statusHeight > 0) {
// 状态栏高度
return statusHeight;
} else {
// 默认值24dp
return (int) (24 * context.getResources().getDisplayMetrics().density + 0.5f);
}
}
/**
* 获取屏幕宽度
*
* @param activity
* @return
*/
public static int getScreenWidth(Activity activity) {
WindowManager wm = activity.getWindowManager();
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
return dm.widthPixels;
}
/**
* 获取屏幕高度
*
* @param activity
* @return
*/
public static int getScreenHeight(Activity activity) {
WindowManager wm = activity.getWindowManager();
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
return dm.heightPixels;
}
/**
* dp值转px值
*
* @param context
* @param dpValue
* @return
*/
public static int dpToPx(Context context, float dpValue) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* px值转dp值
*
* @param context
* @param pxValue
* @return
*/
private int pxToDp(Context context, float pxValue) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
/**
* sp值转px值
*
* @param context
* @param spValue
* @return
*/
public static int spToPx(Context context, float spValue) {
float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
/**
* px值转sp值
*
* @param context
* @param pxValue
* @return
*/
private int pxToSp(Context context, float pxValue) {
float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue / fontScale + 0.5f);
}
/**
* 判断当前网络是否已连接
*
* @param context
* @return
*/
public static boolean isNetworkConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return (ni != null) && (ni.isConnectedOrConnecting());
}
/**
* 判断当前wifi是否可用
*
* @param context
* @return
*/
public static boolean isWifiDataEnable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
}
}