1365 lines
52 KiB
Java
1365 lines
52 KiB
Java
package com.uiui.sn.utils;
|
||
|
||
import android.annotation.SuppressLint;
|
||
import android.app.ActivityManager;
|
||
import android.app.admin.DevicePolicyManager;
|
||
import android.bluetooth.BluetoothAdapter;
|
||
import android.bluetooth.BluetoothDevice;
|
||
import android.content.ActivityNotFoundException;
|
||
import android.content.ComponentName;
|
||
import android.content.Context;
|
||
import android.content.ContextWrapper;
|
||
import android.content.Intent;
|
||
import android.content.IntentFilter;
|
||
import android.content.SharedPreferences;
|
||
import android.content.pm.ApplicationInfo;
|
||
import android.content.pm.PackageInfo;
|
||
import android.content.pm.PackageManager;
|
||
import android.content.pm.PackageManager.NameNotFoundException;
|
||
import android.content.pm.ResolveInfo;
|
||
import android.content.res.Resources;
|
||
import android.graphics.Bitmap;
|
||
import android.graphics.BitmapFactory;
|
||
import android.graphics.Canvas;
|
||
import android.graphics.Paint;
|
||
import android.graphics.PorterDuff;
|
||
import android.graphics.PorterDuffXfermode;
|
||
import android.net.ConnectivityManager;
|
||
import android.net.NetworkInfo;
|
||
import android.net.Uri;
|
||
import android.net.wifi.WifiInfo;
|
||
import android.net.wifi.WifiManager;
|
||
import android.os.BatteryManager;
|
||
import android.os.Build;
|
||
import android.os.StatFs;
|
||
import android.os.SystemClock;
|
||
import android.provider.Settings;
|
||
import android.telephony.TelephonyManager;
|
||
import android.text.TextUtils;
|
||
import android.text.format.Formatter;
|
||
import android.util.DisplayMetrics;
|
||
import android.util.Log;
|
||
import android.view.MotionEvent;
|
||
import android.view.View;
|
||
import android.view.WindowManager;
|
||
import android.view.inputmethod.InputMethodManager;
|
||
import android.widget.EditText;
|
||
import android.widget.Toast;
|
||
|
||
import androidx.annotation.VisibleForTesting;
|
||
|
||
import com.alibaba.fastjson.JSON;
|
||
import com.alibaba.fastjson.JSONObject;
|
||
import com.google.zxing.BarcodeFormat;
|
||
import com.google.zxing.EncodeHintType;
|
||
import com.google.zxing.WriterException;
|
||
import com.google.zxing.common.BitMatrix;
|
||
import com.google.zxing.qrcode.QRCodeWriter;
|
||
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
|
||
import com.uiui.sn.BuildConfig;
|
||
import com.uiui.sn.R;
|
||
import com.uiui.sn.Statistics.AppInformation;
|
||
import com.uiui.sn.Statistics.StatisticsInfo;
|
||
import com.uiui.sn.bean.AppUsed;
|
||
import com.uiui.sn.config.CommonConfig;
|
||
import com.uiui.sn.network.NetInterfaceManager;
|
||
|
||
import java.io.BufferedReader;
|
||
import java.io.File;
|
||
import java.io.FileFilter;
|
||
import java.io.FileNotFoundException;
|
||
import java.io.FileReader;
|
||
import java.io.IOException;
|
||
import java.io.InputStreamReader;
|
||
import java.io.LineNumberReader;
|
||
import java.io.Reader;
|
||
import java.lang.reflect.Method;
|
||
import java.net.NetworkInterface;
|
||
import java.net.SocketException;
|
||
import java.security.MessageDigest;
|
||
import java.security.NoSuchAlgorithmException;
|
||
import java.text.SimpleDateFormat;
|
||
import java.util.ArrayList;
|
||
import java.util.Arrays;
|
||
import java.util.Calendar;
|
||
import java.util.Collections;
|
||
import java.util.Date;
|
||
import java.util.HashMap;
|
||
import java.util.HashSet;
|
||
import java.util.Iterator;
|
||
import java.util.List;
|
||
import java.util.Map;
|
||
import java.util.Set;
|
||
import java.util.regex.Pattern;
|
||
|
||
import static android.content.Context.WIFI_SERVICE;
|
||
|
||
public class Utils {
|
||
private static final String TAG = Utils.class.getSimpleName();
|
||
|
||
// MD5 设备地址标识
|
||
public static String getMAC(Context context) {
|
||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // 如果当前设备系统大于等于6.0 使用下面的方法
|
||
return getMac();
|
||
} else {
|
||
try {
|
||
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
|
||
// 获取MAC地址
|
||
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
|
||
String mac = wifiInfo.getMacAddress();
|
||
if (null == mac) {
|
||
// 未获取到
|
||
mac = "";
|
||
}
|
||
return mac;
|
||
} catch (Exception e) {
|
||
e.printStackTrace();
|
||
return "";
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 获取手机的MAC地址
|
||
*
|
||
* @return
|
||
*/
|
||
public static String getMac() {
|
||
String str = "";
|
||
String macSerial = "";
|
||
try {
|
||
Process pp = Runtime.getRuntime().exec(
|
||
"cat /sys/class/net/wlan0/address");
|
||
InputStreamReader ir = new InputStreamReader(pp.getInputStream());
|
||
LineNumberReader input = new LineNumberReader(ir);
|
||
for (; null != str; ) {
|
||
str = input.readLine();
|
||
if (str != null) {
|
||
macSerial = str.trim();// 去空格
|
||
break;
|
||
}
|
||
}
|
||
} catch (Exception ex) {
|
||
ex.printStackTrace();
|
||
}
|
||
if (macSerial == null || "".equals(macSerial)) {
|
||
try {
|
||
return loadFileAsString("/sys/class/net/eth0/address")
|
||
.toUpperCase().substring(0, 17);
|
||
} catch (Exception e) {
|
||
e.printStackTrace();
|
||
macSerial = getAndroid7MAC();
|
||
}
|
||
}
|
||
return macSerial;
|
||
}
|
||
|
||
/**
|
||
* 兼容7.0获取不到的问题
|
||
*
|
||
* @return
|
||
*/
|
||
public static String getAndroid7MAC() {
|
||
try {
|
||
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
|
||
for (NetworkInterface nif : all) {
|
||
if (!"wlan0".equalsIgnoreCase(nif.getName()))
|
||
continue;
|
||
byte[] macBytes = nif.getHardwareAddress();
|
||
if (macBytes == null) {
|
||
return "";
|
||
}
|
||
StringBuilder res1 = new StringBuilder();
|
||
for (byte b : macBytes) {
|
||
res1.append(String.format("%02X:", b));
|
||
}
|
||
if (res1.length() > 0) {
|
||
res1.deleteCharAt(res1.length() - 1);
|
||
}
|
||
return res1.toString();
|
||
}
|
||
} catch (Exception ex) {
|
||
}
|
||
return "";
|
||
}
|
||
|
||
public static String loadFileAsString(String fileName) throws Exception {
|
||
FileReader reader = new FileReader(fileName);
|
||
String text = loadReaderAsString(reader);
|
||
reader.close();
|
||
return text;
|
||
}
|
||
|
||
public static String loadReaderAsString(Reader reader) throws Exception {
|
||
StringBuilder builder = new StringBuilder();
|
||
char[] buffer = new char[4096];
|
||
int readLength = reader.read(buffer);
|
||
while (readLength >= 0) {
|
||
builder.append(buffer, 0, readLength);
|
||
readLength = reader.read(buffer);
|
||
}
|
||
return builder.toString();
|
||
}
|
||
|
||
// MD5 设备地址标识
|
||
public static String getMD5(Context context) {
|
||
String WLANMAC = getMAC(context);
|
||
// compute md5
|
||
MessageDigest m = null;
|
||
try {
|
||
m = MessageDigest.getInstance("MD5");
|
||
} catch (NoSuchAlgorithmException e) {
|
||
e.printStackTrace();
|
||
}
|
||
if (WLANMAC != null && !"".equals(WLANMAC)) {
|
||
m.update(WLANMAC.getBytes(), 0, WLANMAC.length());
|
||
} else if (getSimSerialNumber(context) != null && !"".equals(getSimSerialNumber(context))) {
|
||
m.update(getSimSerialNumber(context).getBytes(), 0, getSimSerialNumber(context).length());
|
||
} else {
|
||
m.update(getPesudoUniqueID().getBytes(), 0, getPesudoUniqueID().length());
|
||
}
|
||
// get md5 bytes
|
||
byte[] p_md5Data = m.digest();
|
||
// create a hex string
|
||
String m_szUniqueID = new String();
|
||
for (int i = 0; i < p_md5Data.length; i++) {
|
||
int b = (0xFF & p_md5Data[i]);
|
||
// if it is a single digit, make sure it have 0 in front (proper padding)
|
||
if (b <= 0xF)
|
||
m_szUniqueID += "0";
|
||
// add number to string
|
||
m_szUniqueID += Integer.toHexString(b);
|
||
} // hex string to uppercase
|
||
m_szUniqueID = m_szUniqueID.toUpperCase();
|
||
return m_szUniqueID;
|
||
}
|
||
|
||
private static String getSimSerialNumber(Context context) {
|
||
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
|
||
|
||
@SuppressLint("MissingPermission") String simSerialNumber = tm.getSimSerialNumber();
|
||
return simSerialNumber;
|
||
}
|
||
|
||
private static String getPesudoUniqueID() {
|
||
String m_szDevIDShort = "35" + //we make this look like a valid IMEI
|
||
Build.BOARD.length() % 10 +
|
||
Build.BRAND.length() % 10 +
|
||
Build.CPU_ABI.length() % 10 +
|
||
Build.DEVICE.length() % 10 +
|
||
Build.DISPLAY.length() % 10 +
|
||
Build.HOST.length() % 10 +
|
||
Build.ID.length() % 10 +
|
||
Build.MANUFACTURER.length() % 10 +
|
||
Build.MODEL.length() % 10 +
|
||
Build.PRODUCT.length() % 10 +
|
||
Build.TAGS.length() % 10 +
|
||
Build.TYPE.length() % 10 +
|
||
Build.USER.length() % 10;
|
||
return m_szDevIDShort;
|
||
}
|
||
|
||
// 防止连续点击
|
||
private static long lastClickTime;
|
||
|
||
public static boolean isFastDoubleClick() {
|
||
long time = System.currentTimeMillis();
|
||
long timeD = time - lastClickTime;
|
||
if (0 < timeD && timeD < 500) {
|
||
return true;
|
||
}
|
||
lastClickTime = time;
|
||
return false;
|
||
}
|
||
|
||
// 5分钟 = 1 转换成时间
|
||
public static String getRangeTime(int range) {
|
||
StringBuffer sBuffer = new StringBuffer();
|
||
String hour;
|
||
String minute;
|
||
if ((range / 12) >= 10) {
|
||
hour = range / 12 + "";
|
||
} else {
|
||
hour = "0" + range / 12 + "";
|
||
}
|
||
if ((range % 12) > 0) {
|
||
minute = ":" + range % 12 / 2 + "0";
|
||
} else {
|
||
minute = ":00";
|
||
}
|
||
sBuffer.append(hour.trim());
|
||
sBuffer.append(minute.trim());
|
||
return sBuffer.toString();
|
||
}
|
||
|
||
// 根据日期取得星期几
|
||
public static String getWeek(Date date) {
|
||
String[] weeks = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
|
||
Calendar cal = Calendar.getInstance();
|
||
cal.setTime(date);
|
||
int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
|
||
if (week_index < 0) {
|
||
week_index = 0;
|
||
}
|
||
return weeks[week_index];
|
||
}
|
||
|
||
// 非空判断
|
||
public static boolean isEmpty(String s) {
|
||
if (null == s)
|
||
return true;
|
||
if (s.length() == 0)
|
||
return true;
|
||
if (s.trim().length() == 0)
|
||
return true;
|
||
return false;
|
||
}
|
||
|
||
// 手动隐藏键盘
|
||
public static void CloseKeyBoard(Context context) {
|
||
InputMethodManager imm = (InputMethodManager) context
|
||
.getSystemService(Context.INPUT_METHOD_SERVICE);
|
||
System.out.println("isActive:" + imm.isActive());
|
||
if (imm.isActive()) {
|
||
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
|
||
InputMethodManager.HIDE_NOT_ALWAYS);
|
||
}
|
||
}
|
||
|
||
// 接受软键盘输入
|
||
public static void hideKeyboard(Context context, View view) {
|
||
if (context == null || view == null) {
|
||
return;
|
||
}
|
||
InputMethodManager imm = (InputMethodManager) context
|
||
.getSystemService(Context.INPUT_METHOD_SERVICE);
|
||
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
|
||
}
|
||
|
||
// 卸载app
|
||
public static void unInstallAPP(Context context, String packageName) {
|
||
if (!TextUtils.isEmpty(packageName) && !AppsManagerUtils.isSystemApp(context, packageName)) {
|
||
if (AppsManagerUtils.isSystemApp(context, packageName)) {
|
||
ToastUtil.show("系统应用无法卸载!");
|
||
} else {
|
||
Uri packageURI = Uri.parse("package:" + packageName);
|
||
Intent intent = new Intent(Intent.ACTION_DELETE, packageURI);
|
||
context.startActivity(intent);
|
||
}
|
||
} else {
|
||
ToastUtil.show("系统应用无法卸载!");
|
||
}
|
||
}
|
||
|
||
// 打开app
|
||
public static void startApp(Context context, String packageName, String activityName) {
|
||
if (TextUtils.isEmpty(packageName))
|
||
return;
|
||
try {
|
||
Intent intent = null;
|
||
if (TextUtils.isEmpty(activityName)) {
|
||
intent = context.getPackageManager().getLaunchIntentForPackage(
|
||
packageName);
|
||
} else {
|
||
intent = new Intent();
|
||
intent.setComponent(new ComponentName(packageName, activityName));
|
||
}
|
||
if (intent == null) {
|
||
intent = getLaunchIntentForNoCategory(context, packageName);
|
||
}
|
||
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
|
||
context.startActivity(intent);
|
||
} catch (ActivityNotFoundException e) {
|
||
e.printStackTrace();
|
||
} catch (Exception e) {
|
||
e.printStackTrace();
|
||
}
|
||
}
|
||
|
||
public static Intent getLaunchIntentForNoCategory(Context context, String packageName) {
|
||
Intent intent = null;
|
||
PackageManager packageManager = context.getPackageManager();
|
||
PackageInfo packageinfo = null;
|
||
try {
|
||
packageinfo = packageManager.getPackageInfo(packageName, 0);
|
||
} catch (NameNotFoundException e) {
|
||
e.printStackTrace();
|
||
}
|
||
if (packageinfo == null) {
|
||
return null;
|
||
}
|
||
Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
|
||
resolveIntent.setPackage(packageinfo.packageName);
|
||
List<ResolveInfo> resolveinfoList = packageManager.queryIntentActivities(resolveIntent, 0);
|
||
ResolveInfo resolveinfo = resolveinfoList.iterator().next();
|
||
if (resolveinfo != null) {
|
||
String className = resolveinfo.activityInfo.name;
|
||
intent = new Intent(Intent.ACTION_MAIN);
|
||
intent.addCategory(Intent.CATEGORY_LAUNCHER);
|
||
ComponentName cn = new ComponentName(packageName, className);
|
||
intent.setComponent(cn);
|
||
}
|
||
return intent;
|
||
}
|
||
|
||
// 设置系统亮度模式
|
||
public static void systemBrightness(Context context) {
|
||
try {
|
||
SharedPreferences mPrefs = context.getSharedPreferences("colorflykids", 0);
|
||
boolean initSetting = mPrefs.getBoolean("init_setting", true);
|
||
if (initSetting) {
|
||
mPrefs.edit().putBoolean("init_setting", false).commit();
|
||
}
|
||
JGYUtils.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, 0);
|
||
mPrefs.edit().putBoolean("first_init", false).commit();
|
||
} catch (Exception err) {
|
||
err.printStackTrace();
|
||
}
|
||
}
|
||
|
||
// 更新 版本比较
|
||
public static boolean isUpdate(String oldVersion, String newVersion) {
|
||
if (TextUtils.isEmpty(oldVersion) || TextUtils.isEmpty(newVersion) || oldVersion.equals(newVersion)) {
|
||
return false;
|
||
}
|
||
String[] oldVersionSp = oldVersion.replaceAll("[^.\\d]", "").trim().split("\\.");
|
||
String[] newVsersionSp = newVersion.replaceAll("[^.\\d]", "").trim().split("\\.");
|
||
int index = 0;
|
||
int minLen = Math.min(oldVersionSp.length, newVsersionSp.length);
|
||
int diff = 0;
|
||
while (index < minLen && (diff = Integer.parseInt(newVsersionSp[index]) - Integer.parseInt(oldVersionSp[index])) == 0) {
|
||
index++;
|
||
}
|
||
if (diff == 0) {
|
||
for (int i = index; i < oldVersionSp.length; i++) {
|
||
if (Integer.parseInt(oldVersionSp[i]) > 0) {
|
||
return false;
|
||
}
|
||
}
|
||
for (int i = index; i < newVsersionSp.length; i++) {
|
||
if (Integer.parseInt(newVsersionSp[i]) > 0) {
|
||
return true;
|
||
}
|
||
}
|
||
} else {
|
||
return diff > 0 ? true : false;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
/***
|
||
* 半角转换为全角
|
||
*
|
||
* @param input
|
||
* @return
|
||
*/
|
||
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);
|
||
}
|
||
|
||
|
||
protected static Toast toast = null;
|
||
private static String oldMsg;
|
||
private static long oneTime = 0;
|
||
private static long twoTime = 0;
|
||
|
||
public static void showToast(Context context, String s) {
|
||
if (toast == null) {
|
||
toast = Toast.makeText(context, s, Toast.LENGTH_SHORT);
|
||
toast.show();
|
||
oneTime = System.currentTimeMillis();
|
||
} else {
|
||
twoTime = System.currentTimeMillis();
|
||
if (s.equals(oldMsg)) {
|
||
if (twoTime - oneTime > Toast.LENGTH_SHORT) {
|
||
toast.show();
|
||
}
|
||
} else {
|
||
oldMsg = s;
|
||
toast.setText(s);
|
||
toast.show();
|
||
}
|
||
}
|
||
oneTime = twoTime;
|
||
}
|
||
|
||
public static boolean isShouldHideInput(View v, MotionEvent event) {
|
||
if (v != null && (v instanceof EditText)) {
|
||
int[] leftTop = {0, 0};
|
||
//获取输入框当前的location位置
|
||
v.getLocationInWindow(leftTop);
|
||
int left = leftTop[0];
|
||
int top = leftTop[1];
|
||
int bottom = top + v.getHeight();
|
||
int right = left + v.getWidth();
|
||
if (event.getX() > left && event.getX() < right
|
||
&& event.getY() > top && event.getY() < bottom) {
|
||
// 点击的是输入框区域,保留点击EditText的事件
|
||
return false;
|
||
} else {
|
||
return true;
|
||
}
|
||
}
|
||
return false;
|
||
}
|
||
|
||
public static boolean isIntent(Context context) {
|
||
|
||
ConnectivityManager manager = (ConnectivityManager) context
|
||
.getApplicationContext().getSystemService(
|
||
Context.CONNECTIVITY_SERVICE);
|
||
if (manager == null) {
|
||
return false;
|
||
}
|
||
// 检查网络连接,如果无网络可用,就不需要进行连网操作等
|
||
NetworkInfo networkinfo = manager.getActiveNetworkInfo();
|
||
|
||
if (networkinfo == null || !networkinfo.isAvailable()) {
|
||
return false;
|
||
}
|
||
return true;
|
||
}
|
||
|
||
public static String getTime(int time) {
|
||
int min = time / 60;
|
||
int sec = time % 60;
|
||
if (sec > 0) {
|
||
return String.valueOf(min + 1);
|
||
} else {
|
||
return String.valueOf(min);
|
||
}
|
||
}
|
||
|
||
public static String getTimeClick(int time) {
|
||
StringBuffer timeClick = new StringBuffer();
|
||
int min = time / 60;
|
||
int sec = time % 60;
|
||
timeClick.append(min >= 10 ? (int) Math.ceil(min / 10) : 0)
|
||
.append(min % 10)
|
||
.append(":")
|
||
.append(sec >= 10 ? (int) Math.ceil(sec / 10) : 0)
|
||
.append(sec % 10);
|
||
return timeClick.toString();
|
||
}
|
||
|
||
public static String getVersionName(Context context) {
|
||
// 获取packagemanager的实例
|
||
PackageManager packageManager = context.getPackageManager();
|
||
// getPackageName()是你当前类的包名,0代表是获取版本信息
|
||
PackageInfo packInfo;
|
||
try {
|
||
packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
|
||
String version = packInfo.versionName.replaceAll("[a-zA-Z]", "").trim();
|
||
;
|
||
return version;
|
||
} catch (NameNotFoundException e) {
|
||
e.printStackTrace();
|
||
}
|
||
return "";
|
||
}
|
||
|
||
/**
|
||
* 根据手机的分辨率从 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);
|
||
}
|
||
|
||
public static float dp2px(Resources resources, float dp) {
|
||
final float scale = resources.getDisplayMetrics().density;
|
||
return dp * scale + 0.5f;
|
||
}
|
||
|
||
public static float sp2px(Resources resources, float sp) {
|
||
final float scale = resources.getDisplayMetrics().scaledDensity;
|
||
return sp * scale;
|
||
}
|
||
|
||
public static String getTime() {
|
||
long time = System.currentTimeMillis();//long now = android.os.SystemClock.uptimeMillis();
|
||
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
|
||
Date d1 = new Date(time);
|
||
String t1 = format.format(d1);
|
||
return t1;
|
||
}
|
||
|
||
private static void getAdmin(Context context, ComponentName componentName) {
|
||
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
|
||
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
|
||
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "宏云萌书院OS");
|
||
context.startActivity(intent);
|
||
}
|
||
|
||
/**
|
||
* 获取设备序列号
|
||
*
|
||
* @return
|
||
*/
|
||
@SuppressLint({"MissingPermission", "NewApi"})
|
||
public static String getSerial() {
|
||
String serial = "unknow";
|
||
try {
|
||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {//9.0+
|
||
serial = Build.getSerial();
|
||
} else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {//8.0+
|
||
serial = Build.SERIAL;
|
||
} else {//8.0-
|
||
Class<?> c = Class.forName("android.os.SystemProperties");
|
||
Method get = c.getMethod("get", String.class);
|
||
serial = (String) get.invoke(c, "ro.serialno");
|
||
}
|
||
} catch (Exception e) {
|
||
e.printStackTrace();
|
||
Log.e("e", "读取设备序列号异常:" + e.toString());
|
||
}
|
||
return serial;
|
||
}
|
||
|
||
/**
|
||
* @param context 获取真实的MAC地址
|
||
* @return
|
||
*/
|
||
public static String getAndroid10MAC(Context context) {
|
||
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) {
|
||
return getMacAddress(context);
|
||
} else {
|
||
return getAndroid7MAC();
|
||
}
|
||
}
|
||
|
||
@SuppressLint("HardwareIds")
|
||
@VisibleForTesting
|
||
public static String getMacAddress(Context mContext) {
|
||
WifiManager mWifiManager = (WifiManager) mContext.getSystemService(WIFI_SERVICE);
|
||
final String[] macAddresses = mWifiManager.getFactoryMacAddresses();
|
||
String macAddress = null;
|
||
if (macAddresses != null && macAddresses.length > 0) {
|
||
macAddress = macAddresses[0];
|
||
}
|
||
|
||
if (TextUtils.isEmpty(macAddress)) {
|
||
String mac = getMacFromFile();
|
||
// Add for CTCC Feature:WIFI MAC should be gotten while wifi disabled.
|
||
// Get Wifi MAC from file since we can not get it with WifiManager.
|
||
if (!TextUtils.isEmpty(mac)) {
|
||
macAddress = mac;
|
||
} else {
|
||
macAddress = "未能获取到MAC地址";
|
||
}
|
||
}
|
||
return macAddress.toUpperCase();
|
||
}
|
||
|
||
/**
|
||
* Add for CTCC Feature:WIFI MAC should be gotten while wifi disabled.
|
||
* get Wifi MAC from /mnt/vendor/wifimac.txt
|
||
*
|
||
* @{
|
||
*/
|
||
private static String MACID_FILE_PATH = "/mnt/vendor/wifimac.txt";
|
||
|
||
private static String getMacFromFile() {
|
||
File file = new File(MACID_FILE_PATH);
|
||
BufferedReader reader = null;
|
||
String macAddress = null;
|
||
try {
|
||
reader = new BufferedReader(new FileReader(file));
|
||
String line;
|
||
while ((line = reader.readLine()) != null) {
|
||
macAddress = line;
|
||
break;
|
||
}
|
||
} catch (FileNotFoundException e) {
|
||
Log.w(TAG, "Mac file not exist", e);
|
||
} catch (Exception e) {
|
||
Log.w(TAG, "get mac from file caught exception", e);
|
||
} finally {
|
||
try {
|
||
if (reader != null)
|
||
reader.close();
|
||
} catch (IOException e) {
|
||
Log.w(TAG, "reader close exception");
|
||
}
|
||
}
|
||
return macAddress;
|
||
}
|
||
|
||
public static final long A_GB = 1073741824;
|
||
public static final long A_MB = 1048576;
|
||
public static final int A_KB = 1024;
|
||
|
||
public static String fmtSpace(long space) {
|
||
if (space <= 0) {
|
||
return "0";
|
||
}
|
||
double gbValue = (double) space / A_GB;
|
||
if (gbValue >= 1) {
|
||
return String.format("%.2fGB", gbValue);
|
||
} else {
|
||
double mbValue = (double) space / A_MB;
|
||
// Log.e("GB", "gbvalue=" + mbValue);
|
||
if (mbValue >= 1) {
|
||
return String.format("%.2fMB", mbValue);
|
||
} else {
|
||
final double kbValue = space / A_KB;
|
||
return String.format("%.2fKB", kbValue);
|
||
}
|
||
}
|
||
}
|
||
|
||
public static String transferLongToDate(Long millSec) {
|
||
|
||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||
|
||
Date date = new Date(millSec);
|
||
|
||
return sdf.format(date);
|
||
|
||
}
|
||
|
||
public static Bitmap createQRImage(String content, int widthPix, int heightPix) {
|
||
try {
|
||
// if (content == null || "".equals(content)) {
|
||
// return false;
|
||
// }
|
||
|
||
//配置参数
|
||
Map<EncodeHintType, Object> hints = new HashMap<>();
|
||
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
|
||
//容错级别
|
||
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
|
||
//设置空白边距的宽度
|
||
hints.put(EncodeHintType.MARGIN, 1); //default is 4
|
||
|
||
// 图像数据转换,使用了矩阵转换
|
||
BitMatrix bitMatrix = null;
|
||
try {
|
||
bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix,
|
||
heightPix, hints);
|
||
} catch (WriterException e) {
|
||
e.printStackTrace();
|
||
}
|
||
int[] pixels = new int[widthPix * heightPix];
|
||
// 下面这里按照二维码的算法,逐个生成二维码的图片,
|
||
// 两个for循环是图片横列扫描的结果
|
||
for (int y = 0; y < heightPix; y++) {
|
||
for (int x = 0; x < widthPix; x++) {
|
||
if (bitMatrix.get(x, y)) {
|
||
pixels[y * widthPix + x] = 0xff0480ff;
|
||
} else {
|
||
pixels[y * widthPix + x] = 0xffffffff;
|
||
}
|
||
}
|
||
}
|
||
|
||
// 生成二维码图片的格式,使用ARGB_8888
|
||
Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
|
||
bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);
|
||
//
|
||
// if (logoBm != null) {
|
||
// bitmap = addLogo(bitmap, logoBm);
|
||
// }
|
||
|
||
//必须使用compress方法将bitmap保存到文件中再进行读取。直接返回的bitmap是没有任何压缩的,
|
||
// 内存消耗巨大!
|
||
return bitmap;
|
||
// return bitmap != null && bitmap.compress(Bitmap.CompressFormat.JPEG, 100);
|
||
} catch (Exception e) {
|
||
e.printStackTrace();
|
||
}
|
||
return null;
|
||
}
|
||
|
||
//判断是否为系统应用
|
||
public static boolean isSystemApp(Context context, String pkgName) {
|
||
boolean isSystemApp = false;
|
||
PackageInfo pi = null;
|
||
try {
|
||
PackageManager pm = context.getPackageManager();
|
||
pi = pm.getPackageInfo(pkgName, 0);
|
||
} catch (NameNotFoundException e) {
|
||
e.printStackTrace();
|
||
Log.e("isSystemApp", e.getMessage(), e);
|
||
|
||
}
|
||
// 是系统中已安装的应用
|
||
if (pi != null) {
|
||
boolean isSysApp = (pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1;
|
||
boolean isSysUpd = (pi.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) == 1;
|
||
isSystemApp = isSysApp || isSysUpd;
|
||
}
|
||
return isSystemApp;
|
||
}
|
||
|
||
public static Bitmap getRoundedBitmap(Bitmap mBitmap, Context context) {
|
||
Bitmap bgBitmap = Bitmap.createBitmap(mBitmap.getWidth(), mBitmap.getHeight(), Bitmap.Config.ARGB_8888);
|
||
|
||
Bitmap mask = BitmapFactory.decodeResource(context.getResources(), R.drawable.mask);
|
||
int width = mask.getWidth();
|
||
int height = mask.getHeight();
|
||
Bitmap bitmapScale = Bitmap.createScaledBitmap(mBitmap, width, height, true);
|
||
|
||
// Palette p = Palette.from(mBitmap).generate();
|
||
// Palette.Swatch vibrant = p.getVibrantSwatch();//有活力的
|
||
// int color = vibrant.getRgb(); //样本中的像素数量
|
||
|
||
Bitmap result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
|
||
Canvas canvas = new Canvas();
|
||
Paint paint = new Paint();
|
||
|
||
canvas.setBitmap(result);
|
||
// canvas.drawColor(color);
|
||
canvas.drawBitmap(mask, 0, 0, paint);
|
||
// paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
|
||
canvas.drawBitmap(bitmapScale, 0, 0, paint);
|
||
// return result;
|
||
|
||
Bitmap result2 = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
|
||
Canvas canvas2 = new Canvas();
|
||
Paint paint2 = new Paint();
|
||
canvas2.setBitmap(result2);
|
||
canvas2.drawBitmap(mask, 0, 0, paint2);
|
||
paint2.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
|
||
canvas2.drawBitmap(result, 0, 0, paint2);
|
||
return result2;
|
||
|
||
// Canvas mCanvas = new Canvas();
|
||
// mCanvas.setBitmap(bgBitmap);
|
||
// Paint mPaint = new Paint();
|
||
// RectF mRectM = new RectF(scaleM, scaleM, mBitmap.getWidth() - scaleM, mBitmap.getHeight() - scaleM); //设置剪裁圆角的区域
|
||
// Rect mRect = new Rect(0, 0, mBitmap.getWidth(), mBitmap.getHeight());
|
||
// RectF mRectF = mRectM;
|
||
//
|
||
// float roundPx = 15; //圆角半径
|
||
// mPaint.setAntiAlias(true);
|
||
// //Log.d("wy"+TAG,"mBitmap.getWidth()="+mBitmap.getWidth()+", mBitmap.getHeight()="+mBitmap.getHeight());
|
||
// mCanvas.drawRoundRect(mRectF, roundPx, roundPx, mPaint);
|
||
// mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
|
||
// mCanvas.drawBitmap(mBitmap, mRect, mRect, mPaint);
|
||
// return bgBitmap;
|
||
}
|
||
|
||
/**
|
||
* 更新应用白名单禁止升级
|
||
*
|
||
* @param context
|
||
* @return
|
||
*/
|
||
@SuppressLint("NewApi")
|
||
static synchronized public boolean writeDisableUpdateList(Context context) {
|
||
//允许安装的app
|
||
String now = JGYUtils.getString(context.getContentResolver(), CommonConfig.AOLE_ACTION_APP_FORBID);
|
||
//禁止升级的app
|
||
String upgrade_disallow = Settings.System.getString(context.getContentResolver(), "upgrade_disallow");
|
||
//所有app
|
||
String only_jgy_shortcut_list = Settings.System.getString(context.getContentResolver(), CommonConfig.ONLY_SHORTCUT_LIST);
|
||
Log.e("writeDisableUpdateList", "aole_app_forbid: " + now);
|
||
HashSet<String> nowList = new HashSet<>();
|
||
HashSet<String> disallowList = new HashSet<>();
|
||
HashSet<String> allList = new HashSet<>();
|
||
if (!TextUtils.isEmpty(now)) {
|
||
nowList = new HashSet<>(Arrays.asList(now.trim().replaceAll(" ", "").split(",")));
|
||
}
|
||
if (!TextUtils.isEmpty(upgrade_disallow)) {
|
||
disallowList = new HashSet<>(Arrays.asList(upgrade_disallow.trim().replaceAll(" ", "").split(",")));
|
||
}
|
||
if (!TextUtils.isEmpty(only_jgy_shortcut_list)) {
|
||
allList = new HashSet<>(Arrays.asList(only_jgy_shortcut_list.trim().replaceAll(" ", "").split(",")));
|
||
}
|
||
Log.e("writeDisableUpdateList", "nowList: " + nowList);
|
||
Log.e("writeDisableUpdateList", "upgrade_disallow: " + disallowList);
|
||
Log.e("writeDisableUpdateList", "only_jgy_shortcut_list: " + allList);
|
||
//合并
|
||
allList.addAll(nowList);
|
||
|
||
for (String s : disallowList) {
|
||
if (ApkUtils.isAvailable(context, s)) {
|
||
if (allList.remove(s)) {
|
||
Log.e("writeDisableUpdateList", "remove :" + s);
|
||
} else {
|
||
Log.e("writeDisableUpdateList", "remove failed:" + s);
|
||
}
|
||
//去掉已经安装的
|
||
} else {
|
||
if (!allList.contains(s)) {
|
||
allList.add(s);
|
||
}
|
||
//没有安装就加入进去
|
||
//没有加入会导致安装后卸载不能再安装的情况
|
||
}
|
||
Log.e("writeDisableUpdateList", "allList:" + allList);
|
||
}
|
||
boolean writeSucceed = false;
|
||
if (allList.size() > 0) {
|
||
Log.e("writeDisableUpdateList", "allList: " + allList);
|
||
String list = String.join(",", allList);
|
||
writeSucceed = JGYUtils.putString(context.getContentResolver(), CommonConfig.AOLE_ACTION_APP_FORBID, list);
|
||
Log.e("writeDisableUpdateList", "aole_app_forbid: " + list);
|
||
} else {
|
||
writeSucceed = JGYUtils.putString(context.getContentResolver(), CommonConfig.AOLE_ACTION_APP_FORBID, "Invalid");
|
||
}
|
||
return writeSucceed;
|
||
/*功能和应用安装白名单一样,首先会写入所有的app名单。
|
||
*如果已经安装就从白名单删除,没有安装的不用删除
|
||
*不然会出现安装不上的情况
|
||
*在写入白名单之后和安装完成之后执行
|
||
*/
|
||
}
|
||
|
||
public static String getIMEI(Context context) {
|
||
String IMEI = "unknow";
|
||
String IMEI1, IMEI2, IMEI3;
|
||
//获取手机设备号
|
||
TelephonyManager TelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
|
||
//8.0及以后版本获取
|
||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||
IMEI = TelephonyMgr.getDeviceId();
|
||
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
||
// try {
|
||
// Method method = TelephonyMgr.getClass().getMethod("getImei");
|
||
// IMEI = (String) method.invoke(TelephonyMgr);
|
||
// } catch (Exception e) {
|
||
// e.printStackTrace();
|
||
// Log.e("getIMEI", e.getMessage());
|
||
// }
|
||
// IMEI = TelephonyMgr.getDeviceId();
|
||
|
||
// } else {//9.0到10.0获取
|
||
IMEI = JGYUtils.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
|
||
}
|
||
// Log.e("IMEI:", "IMEI: " + IMEI);
|
||
if (null == IMEI) {
|
||
return "-";
|
||
} else {
|
||
return IMEI.toUpperCase();
|
||
}
|
||
}
|
||
|
||
public static String getAndroiodScreenProperty(Context context) {
|
||
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
|
||
DisplayMetrics dm = new DisplayMetrics();
|
||
wm.getDefaultDisplay().getRealMetrics(dm);
|
||
int width = dm.widthPixels; // 屏幕宽度(像素)
|
||
int height = dm.heightPixels; // 屏幕高度(像素)
|
||
float density = dm.density; // 屏幕密度(0.75 / 1.0 / 1.5)
|
||
int densityDpi = dm.densityDpi; // 屏幕密度dpi(120 / 160 / 240)
|
||
// 屏幕宽度算法:屏幕宽度(像素)/屏幕密度
|
||
int screenWidth = (int) (width / density); // 屏幕宽度(dp)
|
||
int screenHeight = (int) (height / density);// 屏幕高度(dp)
|
||
|
||
// Log.e("h_bl", "屏幕宽度(像素):" + width);
|
||
// Log.e("h_bl", "屏幕高度(像素):" + height);
|
||
// Log.e("h_bl", "屏幕密度(0.75 / 1.0 / 1.5):" + density);
|
||
// Log.e("h_bl", "屏幕密度dpi(120 / 160 / 240):" + densityDpi);
|
||
// Log.e("h_bl", "屏幕宽度(dp):" + screenWidth);
|
||
// Log.e("h_bl", "屏幕高度(dp):" + screenHeight);
|
||
return width + "×" + height;
|
||
}
|
||
|
||
public static String getMacAddress() {
|
||
List<NetworkInterface> interfaces = null;
|
||
try {
|
||
interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
|
||
for (NetworkInterface networkInterface : interfaces) {
|
||
if (networkInterface != null && TextUtils.isEmpty(networkInterface.getName()) == false) {
|
||
if ("wlan0".equalsIgnoreCase(networkInterface.getName())) {
|
||
byte[] macBytes = networkInterface.getHardwareAddress();
|
||
if (macBytes != null && macBytes.length > 0) {
|
||
StringBuilder str = new StringBuilder();
|
||
for (byte b : macBytes) {
|
||
str.append(String.format("%02X:", b));
|
||
}
|
||
if (str.length() > 0) {
|
||
str.deleteCharAt(str.length() - 1);
|
||
}
|
||
return str.toString();
|
||
}
|
||
}
|
||
}
|
||
}
|
||
} catch (SocketException e) {
|
||
e.printStackTrace();
|
||
}
|
||
return "unknown";
|
||
}
|
||
|
||
public static int getBattery(Context context) {
|
||
try {
|
||
BatteryManager batteryManager = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
|
||
return batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
|
||
} catch (Exception e) {
|
||
Log.e("getBattery", "getBattery" + e.getMessage());
|
||
}
|
||
return 0;
|
||
}
|
||
|
||
/**
|
||
* 获取电池容量
|
||
*
|
||
* @param context
|
||
* @return
|
||
*/
|
||
public static double getBatterymAh(Context context) {
|
||
Object mPowerProfile;
|
||
double batteryCapacity = 0; //电池的容量mAh
|
||
final String POWER_PROFILE_CLASS = "com.android.internal.os.PowerProfile";
|
||
try {
|
||
mPowerProfile = Class.forName(POWER_PROFILE_CLASS).getConstructor(Context.class).newInstance(context);
|
||
batteryCapacity = (double) Class.forName(POWER_PROFILE_CLASS).getMethod("getBatteryCapacity").invoke(mPowerProfile);
|
||
Log.e("getBattery", "battery mAh: " + batteryCapacity);
|
||
} catch (Exception e) {
|
||
Log.e("getBattery", "get batteryCapacity mAh error:" + batteryCapacity);
|
||
e.printStackTrace();
|
||
}
|
||
return batteryCapacity;
|
||
}
|
||
|
||
synchronized private static int getBatteryLevel(Context mContext) {
|
||
if (Build.VERSION.SDK_INT >= 21)
|
||
return ((BatteryManager) mContext.getSystemService(Context.BATTERY_SERVICE)).getIntProperty(4);
|
||
Intent intent = (new ContextWrapper(mContext)).registerReceiver(null, new IntentFilter("android.intent.action.BATTERY_CHANGED"));
|
||
return intent.getIntExtra("level", -1) * 100 / intent.getIntExtra("scale", -1);
|
||
}
|
||
|
||
public static int getBatteryPercentage(Context context) {
|
||
|
||
IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
|
||
Intent batteryStatus = context.registerReceiver(null, iFilter);
|
||
|
||
int level = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) : -1;
|
||
int scale = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1) : -1;
|
||
|
||
float batteryPct = level / (float) scale;
|
||
|
||
return (int) (batteryPct * 100);
|
||
}
|
||
|
||
public static int getIsCharging(Context context) {
|
||
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
|
||
Intent batteryStatus = context.registerReceiver(null, ifilter);
|
||
// Are we charging / charged?
|
||
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
|
||
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
|
||
status == BatteryManager.BATTERY_STATUS_FULL;
|
||
|
||
// How are we charging?
|
||
// int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
|
||
// boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
|
||
// boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
|
||
if (isCharging) {
|
||
return 1;
|
||
} else {
|
||
return 0;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* @param context
|
||
* @return 已经使用
|
||
*/
|
||
public static long getUsedMemory(Context context) {
|
||
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
|
||
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
|
||
activityManager.getMemoryInfo(memoryInfo);
|
||
long freeMem = memoryInfo.totalMem - memoryInfo.availMem;
|
||
// Log.e("getHardware", "getFreeMemory: " + freeMem);
|
||
return freeMem;
|
||
}
|
||
|
||
/**
|
||
* 描述:获取可用内存.
|
||
*
|
||
* @param context
|
||
* @return
|
||
*/
|
||
public static long getAvailMemory(Context context) {
|
||
// 获取android当前可用内存大小
|
||
ActivityManager activityManager = (ActivityManager) context
|
||
.getSystemService(Context.ACTIVITY_SERVICE);
|
||
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
|
||
activityManager.getMemoryInfo(memoryInfo);
|
||
// 当前系统可用内存 ,将获得的内存大小规格化
|
||
|
||
return memoryInfo.availMem;
|
||
}
|
||
|
||
/**
|
||
* 描述:总内存.
|
||
*
|
||
* @param context
|
||
* @return
|
||
*/
|
||
public static long getTotalMemory(Context context) {
|
||
// 系统内存信息文件
|
||
String file = "/proc/meminfo";
|
||
String memInfo;
|
||
String[] strs;
|
||
long memory = 0;
|
||
|
||
try {
|
||
FileReader fileReader = new FileReader(file);
|
||
BufferedReader bufferedReader = new BufferedReader(fileReader, 8192);
|
||
// 读取meminfo第一行,系统内存大小
|
||
memInfo = bufferedReader.readLine();
|
||
strs = memInfo.split("\\s+");
|
||
// for (String str : strs) {
|
||
// L.d(AppUtil.class, str + "\t");
|
||
// }
|
||
// 获得系统总内存,单位KB
|
||
memory = Integer.valueOf(strs[1]).intValue();
|
||
bufferedReader.close();
|
||
} catch (Exception e) {
|
||
e.printStackTrace();
|
||
}
|
||
// Byte转位KB或MB
|
||
return memory * 1024;
|
||
}
|
||
|
||
public static float getUse_space(Context context) {
|
||
StatFs sf = new StatFs(context.getCacheDir().getAbsolutePath());
|
||
long availableSize = sf.getAvailableBytes();
|
||
Log.e(TAG, "getUse_space: availableSize = " + availableSize);
|
||
long blockSize = sf.getBlockSize();
|
||
Log.e(TAG, "getUse_space: blockSize = " + blockSize);
|
||
long totalBlocks = sf.getBlockCount();
|
||
Log.e(TAG, "getUse_space: totalBlocks = " + totalBlocks);
|
||
|
||
return (float) 100.0 * ((blockSize * totalBlocks) - availableSize) / (blockSize * totalBlocks);
|
||
}
|
||
|
||
public static String getRemnantSize(Context context) {
|
||
StatFs sf = new StatFs(context.getCacheDir().getAbsolutePath());
|
||
long availableSize = sf.getAvailableBytes();
|
||
return Formatter.formatFileSize(context, availableSize);
|
||
}
|
||
|
||
public static String getUsedSize(Context context) {
|
||
StatFs sf = new StatFs(context.getCacheDir().getAbsolutePath());
|
||
long availableSize = sf.getAvailableBytes();
|
||
long blockSize = sf.getBlockSize();
|
||
long totalBlocks = sf.getBlockCount();
|
||
return Formatter.formatFileSize(context, blockSize * totalBlocks - availableSize);
|
||
}
|
||
|
||
public static String getDataTotalSize(Context context) {
|
||
StatFs sf = new StatFs(context.getCacheDir().getAbsolutePath());
|
||
long blockSize = sf.getBlockSize();
|
||
long totalBlocks = sf.getBlockCount();
|
||
return Formatter.formatFileSize(context, blockSize * totalBlocks);
|
||
}
|
||
|
||
private static int getNumCores() {
|
||
// Private Class to display only CPU devices in the directory listing
|
||
class CpuFilter implements FileFilter {
|
||
@Override
|
||
public boolean accept(File pathname) {
|
||
// Check if filename is "cpu", followed by a single digit number
|
||
if (Pattern.matches("cpu[0-9]", pathname.getName())) {
|
||
return true;
|
||
}
|
||
return false;
|
||
}
|
||
}
|
||
|
||
try {
|
||
// Get directory containing CPU info
|
||
File dir = new File("/sys/devices/system/cpu/");
|
||
// Filter to only list the devices we care about
|
||
File[] files = dir.listFiles(new CpuFilter());
|
||
// Return the number of cores (virtual CPU devices)
|
||
return files.length;
|
||
} catch (Exception e) {
|
||
// Default to return 1 core
|
||
return 1;
|
||
}
|
||
}
|
||
|
||
public static String getMachine(Context context) {
|
||
String device = Build.MODEL;//机型
|
||
String imei = getIMEI(context);
|
||
Log.e(TAG, "getMachine: " + imei);
|
||
String system_version = Build.VERSION.RELEASE;
|
||
String firmware_version = JGYUtils.getRomVersion();
|
||
String rom = JGYUtils.getCustomVersion();
|
||
|
||
String screen_rate = getAndroiodScreenProperty(context);
|
||
JSONObject jsonObject = new JSONObject();
|
||
jsonObject.put("device", device);
|
||
jsonObject.put("imei", imei);
|
||
jsonObject.put("system_version", system_version);
|
||
jsonObject.put("firmware_version", firmware_version);
|
||
jsonObject.put("rom", rom);
|
||
jsonObject.put("screen_rate", screen_rate);
|
||
return jsonObject.toJSONString();
|
||
}
|
||
|
||
public static String getHardware(Context context) {
|
||
int electric = getBattery(context);
|
||
int charging = getIsCharging(context);
|
||
String memory = Formatter.formatFileSize(context, getUsedMemory(context)) + "\t 已用" + "/" + "共" + Formatter.formatFileSize(context, getTotalMemory(context));
|
||
Log.e(TAG, "getHardware: memory = " + memory);
|
||
int use_ram = (int) ((float) (1.0 * getUsedMemory(context)) / (1.0 * getTotalMemory(context)) * 100);
|
||
Log.e(TAG, "getHardware: use_ram = " + use_ram);
|
||
String storage = getUsedSize(context) + "/" + getDataTotalSize(context);
|
||
Log.e(TAG, "getHardware: storage = " + storage);
|
||
double use_space = getUse_space(context);
|
||
Log.e(TAG, "getHardware: use_space = " + use_space);
|
||
long wifi_time = (long) com.uiui.sn.utils.SPUtils.get(context, "wifi_last_connect_time", 0L) / 1000;
|
||
Log.e(TAG, "getHardware: wifi_time" + wifi_time);
|
||
int CPU = getNumCores();
|
||
WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
|
||
// WifiInfo wifiInfo = wifiManager.getConnectionInfo();
|
||
WifiInfo info = wifiManager.getConnectionInfo();
|
||
|
||
JSONObject jsonObject = new JSONObject();
|
||
jsonObject.put("electric", electric);
|
||
jsonObject.put("charging", charging);
|
||
jsonObject.put("memory", memory);
|
||
jsonObject.put("mac", getMAC(context));
|
||
jsonObject.put("storage", storage);
|
||
jsonObject.put("is_wifi", JGYUtils.getInstance().isWifiConnect());
|
||
jsonObject.put("CPU", CPU + "核");
|
||
jsonObject.put("use_space", use_space);
|
||
jsonObject.put("use_ram", use_ram);
|
||
jsonObject.put("wifi_ssid", getWifiSSID(context));
|
||
jsonObject.put("wifi_time", wifi_time);
|
||
jsonObject.put("boot_time", SystemClock.elapsedRealtime());
|
||
jsonObject.put("battery_capacity", getBatterymAh(context));
|
||
jsonObject.put("wifi_signal", info.getRssi());
|
||
jsonObject.put("bluetooth", getBluetoothList());
|
||
Log.e(TAG, "getHardware: " + jsonObject.toJSONString());
|
||
return jsonObject.toJSONString();
|
||
}
|
||
|
||
public static String getWifiSSID(Context context) {
|
||
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
|
||
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
|
||
if (wifiInfo != null) {
|
||
return wifiInfo.getSSID();
|
||
} else {
|
||
return "";
|
||
}
|
||
}
|
||
|
||
public static String getBluetoothList() {
|
||
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
|
||
if (bluetoothAdapter == null) {
|
||
return "没有蓝牙设备";
|
||
} else {
|
||
if (!bluetoothAdapter.isEnabled())//判断蓝牙设备是否已开起
|
||
{
|
||
return "蓝牙未开启";
|
||
// //开起蓝牙设备
|
||
// Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
|
||
// context.startActivity(intent);
|
||
} else {
|
||
Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();
|
||
StringBuilder stringBuilder = new StringBuilder();
|
||
for (Iterator<BluetoothDevice> iterator = devices.iterator(); iterator.hasNext(); ) {
|
||
BluetoothDevice device = iterator.next();
|
||
stringBuilder.append(device.getAlias()).append(";");
|
||
}
|
||
Log.e(TAG, "getBluetoothList: " + stringBuilder.toString());
|
||
return stringBuilder.toString();
|
||
}
|
||
}
|
||
}
|
||
|
||
public static String getAppUsedStatistics(Context context) {
|
||
StatisticsInfo statisticsInfo = new StatisticsInfo(context, 0);
|
||
long totalTime = statisticsInfo.getTotalTime();
|
||
int totalTimes = statisticsInfo.getTotalTimes();
|
||
List<AppInformation> datalist = statisticsInfo.getShowList();
|
||
List<AppUsed> appUsedList = new ArrayList<>();
|
||
for (AppInformation information : datalist) {
|
||
AppUsed used = new AppUsed();
|
||
used.setPackages(information.getPackageName());
|
||
used.setUseTime(information.getUsedTimebyDay() / 1000);
|
||
used.setApp_name(information.getLabel());
|
||
appUsedList.add(used);
|
||
}
|
||
appUsedList.removeIf(appUsed -> appUsed.getUseTime() == 0);
|
||
String jsonString = JSON.toJSONString(appUsedList);
|
||
Log.e(TAG, "getAppUsedStatistics: " + jsonString);
|
||
return jsonString;
|
||
}
|
||
|
||
public static void killBackgroundApp(Context context) {
|
||
List<String> pkgList = ApkUtils.queryFilterAppList(context);
|
||
for (String pkg : pkgList) {
|
||
if (runningAppWhitelist.contains(pkg)) continue;
|
||
killBackgroundProcesses(context, pkg);
|
||
}
|
||
}
|
||
|
||
public static List<String> runningAppWhitelist = new ArrayList<String>() {{
|
||
this.add("com.android.launcher3");
|
||
this.add(BuildConfig.APPLICATION_ID);
|
||
this.add("com.uiui.appstore");
|
||
this.add("com.uiui.os");
|
||
this.add("com.uiui.aios");
|
||
this.add("com.uiui.browser");
|
||
this.add("com.uiui.health");
|
||
}};
|
||
|
||
|
||
public static void killBackgroundProcesses(Context context, String packageName) {
|
||
ActivityManager activityManager;
|
||
try {
|
||
activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
|
||
activityManager.killBackgroundProcesses(packageName);
|
||
Method forceStopPackage = activityManager.getClass()
|
||
.getDeclaredMethod("forceStopPackage", String.class);
|
||
// Log.e(TAG, "killBackgroundProcesses: " + packageName);
|
||
forceStopPackage.setAccessible(true);
|
||
forceStopPackage.invoke(activityManager, packageName);
|
||
} catch (Exception e) {
|
||
Log.e(TAG, "killBackgroundProcesses: " + e.getMessage());
|
||
e.printStackTrace();
|
||
}
|
||
}
|
||
|
||
public static String getWifiAlias(Context context) {
|
||
WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
|
||
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
|
||
if (wifiInfo.getSSID() == null) {
|
||
return "WiFi未连接";
|
||
} else {
|
||
Log.e(TAG, "getWifiAlias: " + wifiInfo.getSSID());
|
||
return wifiInfo.getSSID();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 获取公网IP并保存
|
||
*
|
||
* @param context
|
||
*/
|
||
public static void getPublicIP(Context context) {
|
||
NetInterfaceManager.getInstance().getPublicIP(new NetInterfaceManager.PublicIP() {
|
||
@Override
|
||
public void set(String ip) {
|
||
SPUtils.put(context, "PublicIP", ip);
|
||
Log.e("getPublicIP", "set: " + ip);
|
||
}
|
||
});
|
||
}
|
||
} |