/**
* Created by 马占柱 on 2018/07/31.
*/
public class ApiUtils {
private final int PHONE = 0;//手机号验证
private final int HANZI = 1;//中文、数字或字母
public static String title = "title";
public static String time = "time";
public static String url = "url";
public static String type = "type";
public static String LIST = "LIST";
public static String count = "count";
/**
* MD5加密
*/
public static String md5(String string) {
byte[] hash;
try {
hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Huh, MD5 should be supported?", e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Huh, UTF-8 should be supported?", e);
}
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10) {
hex.append("0");
}
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString();
}
//获取起机器
public static String getAndroid_id(Context context) {
try {
String id = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
return id;
} catch (Exception e) {
return "";
}
}
/**
* 获取版本名称
*/
public static String getVersionName(Context context) throws Exception {
// 获取packagemanager的实例
PackageManager packageManager = context.getPackageManager();
// getPackageName()是你当前类的包名,0代表是获取版本信息
PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
return packInfo.versionName;
}
/**
* 获取当前版本号
*/
public static int getVersionCode(Context context) throws Exception {
// 包管理器 可以获取manifest文件里的信息
PackageManager packageManager = context.getPackageManager();
// 获取包信息 参1 包名 参2 flags 不同的flag获取不同的额外信息 不需要就写0
try {
PackageInfo packageInfo = packageManager.getPackageInfo(
context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
* 得到安装的intent
*
* @param apkFile 。
* @return 。
*/
public static Intent getInstallIntent(File apkFile) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(apkFile.getAbsolutePath())),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
/**
* 获取当前手机系统语言。
*
* @return 返回当前系统语言。例如:当前设置的是“中文-中国”,则返回“zh-CN”
*/
public static String getSystemLanguage() {
return Locale.getDefault().getLanguage();
}
/**
* 获取当前系统上的语言列表(Locale列表)
*
* @return 语言列表
*/
public static Locale[] getSystemLanguageList() {
return Locale.getAvailableLocales();
}
/**
* 获取手机型号
*
* @return 手机型号
*/
public static String getSystemModel() {
return android.os.Build.MODEL;
}
/**
* 获取手机厂商
*
* @return 手机厂商
*/
public static String getDeviceBrand() {
return android.os.Build.BRAND;
}
/**
* 正则表达式
*
* @param phone 手机号
* @param state 0手机号 1中文、数字或字母
* @return 返回
*/
public boolean isPhone(String phone, int state) {
if (state == PHONE) {
telRegex = "0?(13|14|15|18|17|16|19)[0-9]{9}";
} else if (state == HANZI) {
telRegex = "[A-Za-z0-9_-\\u4e00-\\u9fa5]+";
}
if (TextUtils.isEmpty(phone)) {
return false;
} else {
return phone.matches(telRegex);
}
}
/**
* 卸载一个app
*/
public static void uninstall(Context context, String packageName) {
// 通过程序的包名创建URI
Uri packageURI = Uri.parse("package:" + packageName);
// 创建Intent意图
Intent intent = new Intent(Intent.ACTION_DELETE, packageURI);
// 执行卸载程序
context.startActivity(intent);
}
/**
* 静默卸载 仅限特定设备使用
*
* @param context
* @param packageName
*/
public static void uninstallSilent(Context context, String packageName) {
try {
// ToastShow.shortMessage("uninstallSilent");
Uri uri = Uri.parse("package:" + packageName);
Intent installintent = new Intent("android.intent.action.SECURE_UNINSTALL_PACKAGE");
installintent.addCategory(Intent.CATEGORY_DEFAULT);
installintent.setData(uri);
installintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(installintent);
} catch (Exception e) {
e.printStackTrace();
uninstall(context, packageName);
}
}
/**
* 根据包名获取安装的应用的版本号
*
* @param context
* @param packageName
* @return
*/
public static int getVersionCode(Context context, String packageName) {
try {
return context.getPackageManager().getPackageInfo(packageName, 0).versionCode;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 判断手机是否已经安装了,指定包名和版本号的应用
*
* @return
*/
public static boolean isInstalled(Context context, String packageName, int versionCode) {
try {
PackageInfo packageInfo = context.getApplicationContext().getPackageManager().getPackageInfo(packageName, 0);
if (isAvailable(context, packageName) && packageInfo.versionCode == versionCode) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return false;
}
/**
* 检查手机上是否安装了指定包名的软件
*/
public static boolean isAvailable(Context context, String packageName) {
// 获取packagemanager
final PackageManager packageManager = context.getApplicationContext().getPackageManager();
// 获取所有已安装程序的包信息
List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
// 用于存储所有已安装程序的包名
List<String> packageNames = new ArrayList<>();
// 从pinfo中将包名字逐一取出,压入pName list中
if (packageInfos != null) {
for (int i = 0; i < packageInfos.size(); i++) {
String packName = packageInfos.get(i).packageName;
packageNames.add(packName);
}
}
// 判断packageNames中是否有目标程序的包名,有TRUE,没有FALSE
return packageNames.contains(packageName);
}
/**
* 根据文件路径获取包名
*/
public static String getPackageName(Context context, String filePath) {
PackageManager packageManager = context.getApplicationContext().getPackageManager();
PackageInfo info = packageManager.getPackageArchiveInfo(filePath, PackageManager.GET_ACTIVITIES);
if (info != null) {
ApplicationInfo appInfo = info.applicationInfo;
return appInfo.packageName; // 得到安装包名称
}
return null;
}
/**
* 从apk中获取版本信息
*/
@SuppressLint("NewApi")
public static String getChannelFromApk(Context context, String channelPrefix) {
// 从apk包中获取
ApplicationInfo appinfo = context.getApplicationContext().getApplicationInfo();
String sourceDir = appinfo.sourceDir;
// 默认放在meta-inf/里, 所以需要再拼接一下
String key = "META-INF/" + channelPrefix;
String ret = "";
ZipFile zipfile = null;
try {
zipfile = new ZipFile(sourceDir);
Enumeration<?> entries = zipfile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = ((ZipEntry) entries.nextElement());
String entryName = entry.getName();
if (entryName.startsWith(key)) {
ret = entryName;
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (zipfile != null) {
try {
zipfile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String[] split = ret.split(channelPrefix);
String channel = "";
if (split.length >= 2) {
channel = ret.substring(key.length());
}
return channel;
}
/**
* 打开app
*
* @param context
* @param packageName
* @return
*/
public static boolean openPackage(Context context, String packageName) {
Context pkgContext = getPackageContext(context.getApplicationContext(), packageName);
Intent intent = getAppOpenIntentByPackageName(context, packageName);
if (pkgContext != null && intent != null) {
pkgContext.startActivity(intent);
return true;
}
return false;
}
/**
* 打开app
*
* @param context
* @param packageName
* @param activity 三方app对应的启动activity路径
* @return
*/
public static boolean openPackage(Context context, String packageName, String activity) {
Context pkgContext = getPackageContext(context.getApplicationContext(), packageName);
Intent intent = new Intent();
// a应用启动b应用
ComponentName cn = new ComponentName(packageName, activity);
intent.setComponent(cn);
Uri uri = Uri.parse(packageName);// 此处应与B程序中Data中标签一致
intent.setData(uri);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (pkgContext != null && intent != null) {
pkgContext.startActivity(intent);
return true;
}
return false;
}
/**
* 根据包名获取程序 图标
*
* @param context
* @param pkgName
* @return
*/
public static Drawable getAppIcon(Context context, String pkgName) {
try {
ApplicationInfo info = context.getApplicationContext().getPackageManager().getApplicationInfo(pkgName, 0);
return info.loadIcon(context.getPackageManager());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 获取网络类型
*
* @param context
* @return 2G/3G/4G/Wi-Fi
*/
public static String getNetwork(Context context) {
NetworkInfo network = ((ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
String strNetwork = "未知";
if (network != null && network.isAvailable() && network.isConnected()) {
int type = network.getType();
if (type == ConnectivityManager.TYPE_WIFI) {
strNetwork = "Wi-Fi";
} else if (type == ConnectivityManager.TYPE_MOBILE) {
int networkType = network.getSubtype();
switch (networkType) {
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN: //api<8 : replace by 11
strNetwork = "2G";
break;
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B: //api<9 : replace by 14
case TelephonyManager.NETWORK_TYPE_EHRPD: //api<11 : replace by 12
case TelephonyManager.NETWORK_TYPE_HSPAP: //api<13 : replace by 15
strNetwork = "3G";
break;
case TelephonyManager.NETWORK_TYPE_LTE: //api<11 : replace by 13
strNetwork = "4G";
break;
default:
break;
}
}
}
return strNetwork;
}
/**
* 返回运营商
*
* @return 中国移动,中国联通,中国电信,未知
*/
public static String getOperators(Context context) {
try {
// 移动设备网络代码(英语:Mobile Network Code,MNC)是与移动设备国家代码(Mobile Country Code,MCC)(也称为“MCC /
// MNC”)相结合, 例如46000,前三位是MCC,后两位是MNC 获取手机服务商信息
String OperatorsName = "未知";
TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String IMSI = manager.getSubscriberId();
if (IMSI == null) {
return "未知";
}
// IMSI号前面3位460是国家,紧接着后面2位00 运营商代码
if (IMSI.startsWith("46000") || IMSI.startsWith("46002") || IMSI.startsWith("46007")) {
OperatorsName = "中国移动";
} else if (IMSI.startsWith("46001") || IMSI.startsWith("46006")) {
OperatorsName = "中国联通";
} else if (IMSI.startsWith("46003") || IMSI.startsWith("46005")) {
OperatorsName = "中国电信";
} else {
OperatorsName = "未知";
}
return OperatorsName;
} catch (Exception e) {
return "运营商未知";
}
}
/**
* 获取当前手机的ip地址
*/
public static String getIPAddress(Context context) {
NetworkInfo info = ((ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info != null && info.isConnected()) {
if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
//当前使用2G/3G/4G网络
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (info.getType() == ConnectivityManager.TYPE_WIFI) {
//当前使用无线网络
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());
//得到IPV4地址
return ipAddress;
}
} else {
//当前无网络连接,请在设置中打开网络
}
return "ip地址未知";
}
/**
* 将得到的int类型的IP转换为String类型
*
* @param ip
* @return
*/
public static String intIP2StringIP(int ip) {
return (ip & 0xFF) + "." +
((ip >> 8) & 0xFF) + "." +
((ip >> 16) & 0xFF) + "." +
(ip >> 24 & 0xFF);
}
}