package com.aoleyun.sn.utils; import static android.content.Context.WIFI_SERVICE; import android.annotation.SuppressLint; import android.app.ActivityManager; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.bluetooth.BluetoothProfile; 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.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.Environment; 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.RequiresApi; import androidx.annotation.VisibleForTesting; import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory; import com.aoleyun.sn.BuildConfig; import com.aoleyun.sn.R; import com.aoleyun.sn.comm.CommonConfig; import com.aoleyun.sn.manager.AllwinnerCubeMdmManager; import com.arialyy.aria.core.Aria; import com.blankj.utilcode.util.FileUtils; import com.google.gson.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.hjq.toast.Toaster; import java.io.BufferedReader; import java.io.DataOutputStream; 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.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.DecimalFormat; 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.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.core.ObservableEmitter; import io.reactivex.rxjava3.core.ObservableOnSubscribe; import io.reactivex.rxjava3.core.Observer; import io.reactivex.rxjava3.disposables.Disposable; import io.reactivex.rxjava3.schedulers.Schedulers; import vendor.mediatek.hardware.nvram.V1_0.INvram; public class Utils { private static final String TAG = "Utils"; // 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(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; } public static String getAndroid10MAC(Context context) { // if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) { // return getMacAddress(context); // } else { // return getAndroid7MAC(); // } return getAllMacAddress(context); } /** * 兼容7.0获取不到的问题 * * @return */ public static String getAndroid7MAC() { try { List all = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface nif : all) { if (!nif.getName().equalsIgnoreCase("wlan0")) 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 ""; } @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; } /** * 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 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(); } /** * 获取MAC地址 * * @param context * @return */ public static String getAllMacAddress(Context context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return getMacDefault(context); } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { return getMacAddressM(); } else { return getMacFromHardware(); } } /** * Android 6.0 之前(不包括6.0) * * @param context * @return */ private static String getMacDefault(Context context) { String mac = "未获取到设备Mac地址"; if (context == null) { return mac; } WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo info = null; try { info = wifi.getConnectionInfo(); } catch (Exception e) { e.printStackTrace(); } if (info == null) { return mac; } mac = info.getMacAddress(); if (!TextUtils.isEmpty(mac)) { mac = mac.toUpperCase(Locale.ENGLISH); } return mac; } /** * Android 6.0(包括) - Android 7.0(不包括) * * @return */ private static String getMacAddressM() { String mac = "未获取到设备Mac地址"; try { mac = new BufferedReader(new FileReader("/sys/class/net/wlan0/address")).readLine(); } catch (IOException e) { e.printStackTrace(); } return mac; } /** * 遍历循环所有的网络接口,找到接口是 wlan0 * * @return */ private static String getMacFromHardware() { try { List all = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface nif : all) { if (!nif.getName().equalsIgnoreCase("wlan0")) { continue; } byte[] macBytes = nif.getHardwareAddress(); StringBuilder res1 = new StringBuilder(); for (byte b : macBytes) { res1.append(String.format("%02X:", b)); } if (res1 != null) { res1.deleteCharAt(res1.length() - 1); } return res1.toString(); } } catch (Exception e) { e.printStackTrace(); } return "未获取到设备Mac地址"; } private static String getMacAddrApiS(Context context) { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); String mac = wifiInfo.getMacAddress(); return mac; } // 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 && !WLANMAC.equals("")) { m.update(WLANMAC.getBytes(), 0, WLANMAC.length()); } else if (getSimSerialNumber(context) != null && !getSimSerialNumber(context).equals("")) { 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) && !ApkUtils.isSystemApp(context, packageName)) { if (ApkUtils.isSystemApp(context, packageName)) { Toast.makeText(context, R.string.system_unistall_error, Toast.LENGTH_SHORT).show(); } else { Uri packageURI = Uri.parse("package:" + packageName); Intent intent = new Intent(Intent.ACTION_DELETE, packageURI); context.startActivity(intent); } } else { Toast.makeText(context, R.string.unistall_error, Toast.LENGTH_SHORT).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 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(); } Settings.System.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); } 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) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; } //获取App版本号 public static String getAppVersionName(String pck, Context context) { PackageManager pm = context.getPackageManager(); String versionName; try { PackageInfo packageInfo = pm.getPackageInfo(pck, 0); versionName = packageInfo.versionName; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); versionName = ""; } return versionName; } /** * 根据手机的分辨率从 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; } public static final String NOSN = "0123456789ABCDEF"; public static final String TECLAST_BRAND = "Teclast"; /** * 获取设备序列号 * * @return */ public static String getSerial(Context context) { if (JgyUtils.getInstance().checkAppPlatform() == JgyUtils.HL500Platform) { return getIMEI(context); } if (TECLAST_BRAND.equalsIgnoreCase(Build.BRAND)) { return getPushMac(context); } else { // if (NOSN.equalsIgnoreCase(getSn())) { // return getIMEI(context); // } else { return getSn(); // } } } public static String getPushMac(Context context) { String macaddr = Utils.getMacAddrFromNvram(); return macaddr.replace(":", "").toUpperCase().trim(); } //mh add start---- private static final int MAC_ADDRESS_ID = 30; private static final int MAC_ADDRESS_OFFSET = 4; private static final int MAC_ADDRESS_DIGITS = 6; private static final int MAX_ADDRESS_VALUE = 0xff; private static final int INVALID_RSSI = -200; private static final String MAC_ADDRESS_FILENAME = "/mnt/vendor/nvdata/APCFG/APRDEB/WIFI"; private static String getMacAddrFromNvram() { StringBuffer nvramBuf = new StringBuffer(); try { int i = 0; String buff = null; INvram agent = INvram.getService(); if (agent == null) { // mToast.setText("No support MAC address writing due to NVRAM"); // mToast.show(); Log.e("mh_mac", "NvRAMAgent is null"); return ""; } try { buff = agent.readFileByName( MAC_ADDRESS_FILENAME, MAC_ADDRESS_OFFSET + MAC_ADDRESS_DIGITS); } catch (Exception e) { e.printStackTrace(); return ""; } Log.i("mh_mac", "Raw data:" + buff); if (buff.length() < 2 * (MAC_ADDRESS_OFFSET + MAC_ADDRESS_DIGITS)) { // mToast.setText("The foramt of NVRAM is not correct"); // mToast.show(); return ""; } // Remove the \0 special character. int macLen = buff.length() - 1; for (i = MAC_ADDRESS_OFFSET * 2; i < macLen; i += 2) { if ((i + 2) < macLen) { nvramBuf.append(buff.substring(i, i + 2)); nvramBuf.append(":"); } else { nvramBuf.append(buff.substring(i)); } } Log.d("mh_mac", "buff:" + nvramBuf.toString()); } catch (Exception e) { e.printStackTrace(); return ""; } return nvramBuf.toString(); } //mh add end------ @SuppressLint({"MissingPermission", "HardwareIds"}) public static String getSn() { // if (BuildConfig.DEBUG) { // return "LTPHR23040000006"; // } 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("getSerial", "读取设备序列号异常:" + e.toString()); } return serial; } public static String getDeviceSN() { String serial = null; try { Class c = Class.forName("android.os.SystemProperties"); Method get = c.getMethod("get", String.class); serial = (String) get.invoke(c, "persist.sys.hrSerial"); } catch (Exception e) { e.printStackTrace(); } return serial; } /** * @return 获取第三方内置apk */ public static HashSet getPackage() { String packages = ""; try { Class c = Class.forName("android.os.SystemProperties"); Method get = c.getMethod("get", String.class); packages = (String) get.invoke(c, "persist.sys.package"); } catch (Exception e) { e.printStackTrace(); } HashSet packageSet = new HashSet<>(); if (TextUtils.isEmpty(packages)) { return packageSet; } else { packageSet.addAll(Arrays.asList(packages.split(","))); return packageSet; } } 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 Bitmap createQRImage(String content, int widthPix, int heightPix) { try { // if (content == null || "".equals(content)) { // return false; // } //配置参数 Map 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] = 0xff000000; } 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 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 key * @param defaultValue * @return */ public static String getProperty(String key, String defaultValue) { String value = defaultValue; try { Class c = Class.forName("android.os.SystemProperties"); Method get = c.getMethod("get", String.class, String.class); value = (String) (get.invoke(c, key, defaultValue)); } catch (Exception e) { e.printStackTrace(); } finally { return value; } } /** * 重置系统 * * @param context */ public static void doMasterClear(Context context) { if (BuildConfig.DEBUG) { Toaster.show("收到重置设备推送消息"); return; } if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) { Intent intent = new Intent("android.intent.action.FACTORY_RESET"); intent.setPackage("android"); intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); intent.putExtra("android.intent.extra.REASON", "MasterClearConfirm"); intent.putExtra("android.intent.extra.WIPE_EXTERNAL_STORAGE", false); intent.putExtra("com.android.internal.intent.extra.WIPE_ESIMS", false); context.sendBroadcast(intent); } else { //10.0的不需要最小电量 if (getBatteryLevel(context) >= CommonConfig.MIN_POWER) { Intent intent = new Intent("android.intent.action.MASTER_CLEAR"); // intent.setPackage("com.android.settings"); context.sendBroadcast(intent); } else { MySQLData.SetBooleanData(context, CommonConfig.IS_RESET, true); } } } /** * 更新应用白名单禁止升级 * * @param context * @param allowList 禁止 * @param disallowList 允许 * @return */ static public boolean writeDisableUpdateList(Context context, String[] allowList, String[] disallowList) { String now = Settings.System.getString(context.getContentResolver(), CommonConfig.AOLE_ACTION_APP_FORBID); String[] nowList; List allList; if (now == null || "".equalsIgnoreCase(now)) { allList = new ArrayList<>(); } else { nowList = now.split(","); allList = new ArrayList<>(Arrays.asList(nowList));//已经写入的列表 } boolean writeSucceed = false; if (allowList != null && allowList.length > 0) { for (String s : allowList) { if (ApkUtils.isAvailable(context, s)) { allList.remove(s); //去掉已经安装的 } else { if (allList.indexOf(s) == -1) { allList.add(s); } //没有安装就加入进去 //没有加入会导致安装后卸载不能再安装的情况 } } } for (String s : disallowList) { if (allList.indexOf(s) == -1) { allList.add(s); //没找到元素添加到白名单 } } if (allList.size() > 0) { String list = ""; for (String str : allList) { list += str + ","; } list = list.substring(0, list.length() - 1); Log.e("fht", list); writeSucceed = Settings.System.putString(context.getContentResolver(), CommonConfig.AOLE_ACTION_APP_FORBID, list); Log.e("fht", "aole_app_forbid:" + list); } else { writeSucceed = Settings.System.putString(context.getContentResolver(), CommonConfig.AOLE_ACTION_APP_FORBID, ""); } if (JgyUtils.isAllWinnerDevice()) { try { AllwinnerCubeMdmManager.getInstance().setInstallPackageWhiteList(allList); writeSucceed = true; } catch (Exception e) { Log.e(TAG, "writeDisableUpdateList: " + e.getMessage()); writeSucceed = false; } } return writeSucceed; /*功能和应用安装白名单一样,首先会写入所有的app名单。 *如果已经安装就从白名单删除,没有安装的不用删除 *不然会出现安装不上的情况 *在写入白名单之后和安装完成之后执行 */ } /** * 重启设备 * * @param context */ public static void rebootDevices(Context context) { Intent iReboot = new Intent(Intent.ACTION_REBOOT); iReboot.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(iReboot); } public static String getFileNamefromURL(String url) { int position = url.lastIndexOf("/"); return url.substring(position + 1); } private static String getMD5fromFileName(String fileName) { int position = fileName.lastIndexOf("/"); return fileName.substring(position + 13, fileName.length() - 4); } /** * 主要的下载 * * @param context * @param url * @param jsonObject */ public static void ariaDownload(Context context, String url, JsonObject jsonObject) { Log.e(TAG, "ariaDownload: " + jsonObject); String fileName = getFileNamefromURL(url); String urlMD5 = ""; if (jsonObject.get("MD5") == null) { if (jsonObject.get("app_md5") != null) { urlMD5 = jsonObject.get("app_md5").getAsString(); } } else { if (jsonObject.get("MD5") != null) { if (!jsonObject.get("MD5").isJsonNull()) { urlMD5 = jsonObject.get("MD5").getAsString(); } } } Log.e("ariaDownload", "urlMD5=" + urlMD5); String p = JgyUtils.getInstance().getDownLoadPath(); File file = new File(JgyUtils.getInstance().getDownLoadPath() + fileName); if (file.exists() && !file.isDirectory()) { String filenameMD5 = getMD5fromFileName(url); String fileMD5 = FileUtils.getFileMD5ToString(file); Log.e("ariaDownload", "filenameMD5=" + filenameMD5); Log.e("ariaDownload", "fileMD5=" + fileMD5); //后端还没有完成json字段的MD5,暂时用文件名获取 if (fileMD5.equalsIgnoreCase(urlMD5)) { ApkUtils.installApp(context, file.getAbsolutePath()); } else { Aria.download(context) .load(url) //读取下载地址 .setFilePath(JgyUtils.getInstance().getDownLoadPath() + fileName) .ignoreFilePathOccupy() .setExtendField(jsonObject.toString()) .create(); //启动下载} } } else { Aria.download(context) .load(url) //读取下载地址 .setFilePath(JgyUtils.getInstance().getDownLoadPath() + fileName) .ignoreFilePathOccupy() .setExtendField(jsonObject.toString()) .create(); //启动下载} } } private void showToast() { } /** * 屏幕截图 * 适用于lanucher版 */ public static void shotScreen(final Context context) { //adb截图方法 Observable.create(new ObservableOnSubscribe() { @Override public void subscribe(ObservableEmitter e) throws Exception { String filepath = context.getCacheDir().getAbsolutePath(); long time = System.currentTimeMillis(); int n = CmdUtil.execute("screencap -p " + filepath + File.separator + time + ".db").code; e.onNext(n); } }).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(Integer integer) { if (integer == 0) { Log.e("doss", "成功"); } else { Log.e("doss", "失败"); } } @Override public void onError(Throwable e) { Log.e("doss", "Throwable=" + e.getMessage()); } @Override public void onComplete() { } }); // new Thread(new Runnable() { // @Override // public void run() { // Log.e("whh0914", "开始屏幕截图..."); // String filepath = context.getFileStreamPath("screenshot").getAbsolutePath(); // try { // CmdUtil.execute("screencap -p " + filepath); // } catch (Exception e) { // Log.e("whh0914", "屏幕截图出现异常:" + e.toString()); // } // } // }).start(); } /** * 执行命令但不关注结果输出 */ public static int execRootCmdSilent(String cmd) { int result = -1; DataOutputStream dos = null; try { Process p = Runtime.getRuntime().exec("su"); dos = new DataOutputStream(p.getOutputStream()); dos.writeBytes(cmd + "\n"); dos.flush(); dos.writeBytes("exit\n"); dos.flush(); p.waitFor(); result = p.exitValue(); } catch (Exception e) { e.printStackTrace(); } finally { if (dos != null) { try { dos.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } 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("getAndroiodScreenProperty", "屏幕宽度(像素):" + width); Log.e("getAndroiodScreenProperty", "屏幕高度(像素):" + height); Log.e("getAndroiodScreenProperty", "屏幕密度(0.75 / 1.0 / 1.5):" + density); Log.e("getAndroiodScreenProperty", "屏幕密度dpi(120 / 160 / 240):" + densityDpi); Log.e("getAndroiodScreenProperty", "屏幕宽度(dp):" + screenWidth); Log.e("getAndroiodScreenProperty", "屏幕高度(dp):" + screenHeight); return width + "×" + height; } public static int getDensityDpi(Context context) { WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); DisplayMetrics dm = new DisplayMetrics(); wm.getDefaultDisplay().getRealMetrics(dm); return dm.densityDpi; } public static String getMacAddress() { List interfaces = null; try { interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface networkInterface : interfaces) { if (networkInterface != null && !TextUtils.isEmpty(networkInterface.getName())) { 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"; } @SuppressLint("HardwareIds") public static String getIMEI(Context context, int slotIndex) { String imei; TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { imei = tm.getImei(slotIndex); } else { imei = tm.getDeviceId(slotIndex); } if (TextUtils.isEmpty(imei)) { return context.getString(R.string.no_data); } return imei; } @SuppressLint("HardwareIds") public static String getIMEI(Context context) { String IMEI = "unknow"; //获取手机设备号 TelephonyManager TelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); //8.0及以后版本获取 if (android.os.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 = Settings.System.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID); } Log.e("IMEI:", "IMEI: " + IMEI); if (null == IMEI) { return ""; } else { return IMEI.toUpperCase(); } } /** * IMEI 1号 * * @param context * @return */ // public static String getIMEI_1(Context context) { // TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); // return tm != null ? tm.getDeviceId() : ""; // } /** * IMEI 2号 * * @param context * @return */ // public static String getIMEI_2(Context context) { // TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); // Class clazz = tm.getClass(); // try { // Method getImei = clazz.getDeclaredMethod("getImei", int.class); // return getImei.invoke(tm, 1).toString(); // } catch (NoSuchMethodException e) { // e.printStackTrace(); // } catch (InvocationTargetException e) { // e.printStackTrace(); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // return ""; // } public static String getMachine(Context context) { String device = Build.MODEL;//机型 String imei = getIMEI(context); String system_version = Build.VERSION.RELEASE; String firmware_version = getRomVersion(); String rom = Utils.getCustomVersion(); String screen_rate = getAndroiodScreenProperty(context); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("device", device); jsonObject.addProperty("imei", imei); jsonObject.addProperty("system_version", system_version); jsonObject.addProperty("firmware_version", firmware_version); jsonObject.addProperty("rom", rom); jsonObject.addProperty("screen_rate", screen_rate); jsonObject.addProperty("working_time", SystemClock.elapsedRealtime() / 1000); jsonObject.addProperty("restart_count", (int) SPUtils.get(context, "restart_count", 0)); jsonObject.addProperty("storage_usable", getDataTotalSizeGb(context)); jsonObject.addProperty("storage_total", getDataTotalSizeGb(context)); String jsonString = jsonObject.toString(); Log.e(TAG, "getMachine: " + jsonString); return jsonString; } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public static String getHardware(Context context) { int electric = getBattery(context); int charging = getIsCharging(context); String memory = Formatter.formatFileSize(context, getFreeMemory(context)) + "\t 已用" + "/" + "共" + Formatter.formatFileSize(context, getTotalMemory(context)); Log.e("getHardware", "Memory: " + memory); String storage = getRemnantSize(context) + "/" + getDataTotalSize(context); int CPU = getNumCores(); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("electric", electric); jsonObject.addProperty("charging", charging); jsonObject.addProperty("memory", memory); jsonObject.addProperty("memory_used", Utils.getSizeGb(getFreeMemory(context))); jsonObject.addProperty("memory_total", Utils.getSizeGb(getTotalMemory(context))); jsonObject.addProperty("storage", storage); jsonObject.addProperty("battery_capacity", Utils.getBatterymAh(context)); jsonObject.addProperty("CPU", CPU + "核"); String jsonString = jsonObject.toString(); Log.e(TAG, "getHardware: " + jsonString); return jsonString; } public static String getAddressJsonString(Context context) { String address = String.valueOf(SPUtils.get(context, "MapAddress", "-")); if ("-".equals(address)) { address = "定位失败"; } String longitude = String.valueOf(SPUtils.get(context, "longitude", "0")); String latitude = String.valueOf(SPUtils.get(context, "latitude", "0")); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("address", address); jsonObject.addProperty("longitude", longitude); jsonObject.addProperty("latitude", latitude); String jsonString = jsonObject.toString(); Log.e(TAG, "getAddressJsonString: " + jsonString); return jsonString; } public static String getOtherInfo() { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("push_id", PushServiceFactory.getCloudPushService().getDeviceId()); String jsonString = jsonObject.toString(); Log.e(TAG, "getOtherInfo: push_id = " + jsonString); return jsonString; } 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; } } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public static int getBattery(Context context) { try { BatteryManager batteryManager = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE); if (batteryManager == null) { return 0; } int capacity = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY); // -1 表示设备无法获取电量(无电池或底层未上报),归一到 0 避免下游误判 if (capacity < 0 || capacity > 100) { return 0; } return 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; } /** * 获取电量 * * @param mContext * @return */ private static int getBatteryLevel(Context mContext) { if (Build.VERSION.SDK_INT >= 21) { return ((BatteryManager) mContext.getSystemService(Context.BATTERY_SERVICE)).getIntProperty(4); } else { 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 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 getFreeMemory(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 getTotalMemory(Context context) { ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo(); activityManager.getMemoryInfo(memoryInfo); // Log.e("getHardware", "getFreeMemory: " + memoryInfo.totalMem); return memoryInfo.totalMem; } /** * 描述:总内存. * https://blog.csdn.net/a357339414/article/details/52057507 * * @return */ public static long getTotalMemory() { // 系统内存信息文件 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; // return memory * 1000; } public static String formatFileSize(long fileS) { DecimalFormat df = new DecimalFormat("#.0"); String fileSizeString = ""; String wrongSize = "0B"; if (fileS == 0) { return wrongSize; } if (fileS < 1024) { fileSizeString = df.format((double) fileS) + "B"; } else if (fileS < 1048576) { fileSizeString = df.format((double) fileS / 1024) + "KB"; } else if (fileS < 1073741824) { fileSizeString = df.format((double) fileS / 1048576) + "MB"; } else { fileSizeString = df.format((double) fileS / 1073741824) + "GB"; } return fileSizeString; } public static void queryStorage() { StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getPath()); //存储块总数量 long blockCount = statFs.getBlockCount(); //块大小 long blockSize = statFs.getBlockSize(); //可用块数量 long availableCount = statFs.getAvailableBlocks(); //剩余块数量,注:这个包含保留块(including reserved blocks)即应用无法使用的空间 long freeBlocks = statFs.getFreeBlocks(); //这两个方法是直接输出总内存和可用空间,也有getFreeBytes //API level 18(JELLY_BEAN_MR2)引入 long totalSize = statFs.getTotalBytes(); long availableSize = statFs.getAvailableBytes(); Log.e("statfs", "total = " + getUnit(totalSize)); Log.e("statfs", "availableSize = " + getUnit(availableSize)); //这里可以看出 available 是小于 free ,free 包括保留块。 Log.e("statfs", "total = " + getUnit(blockSize * blockCount)); Log.e("statfs", "available = " + getUnit(blockSize * availableCount)); Log.e("statfs", "free = " + getUnit(blockSize * freeBlocks)); } private static String[] units = {"B", "KB", "MB", "GB", "TB"}; /** * 单位转换 */ private static String getUnit(float size) { int index = 0; while (size > 1024 && index < 4) { size = size / 1024; index++; } return String.format(Locale.getDefault(), " %.2f %s", size, units[index]); } public static String getSizeGb(long size) { DecimalFormat df = new DecimalFormat("#.00"); return df.format((double) size / 1073741824); } public static String getDataTotalSizeGb(Context context) { StatFs sf = new StatFs(context.getCacheDir().getAbsolutePath()); long blockSize = sf.getBlockSize(); long totalBlocks = sf.getBlockCount(); return getSizeGb(blockSize * totalBlocks); } public static String getRemnantSizeGb(Context context) { StatFs sf = new StatFs(context.getCacheDir().getAbsolutePath()); long availableSize = sf.getAvailableBytes(); return getSizeGb(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); } public static String getRemnantSize(Context context) { StatFs sf = new StatFs(context.getCacheDir().getAbsolutePath()); long availableSize = sf.getAvailableBytes(); return Formatter.formatFileSize(context, availableSize); } /** * 获取自定义版本号 或者版本号 * * @return */ public static String getCustomVersion() { if (JgyUtils.getInstance().checkAppPlatform() == JgyUtils.ZhanruiPlatform // || JgyUtils.getInstance().checkAppPlatform() == JgyUtils.CubePlatform || JgyUtils.getInstance().checkAppPlatform() == JgyUtils.MTKPlatform || JgyUtils.getInstance().checkAppPlatform() == JgyUtils.MTK11Platform || JgyUtils.getInstance().checkAppPlatform() == JgyUtils.TeclastP20sPlatform || JgyUtils.getInstance().checkAppPlatform() == JgyUtils.AH6016Platform || JgyUtils.getInstance().checkAppPlatform() == JgyUtils.ZR6016Platform || JgyUtils.getInstance().checkAppPlatform() == JgyUtils.HRAD13Platform || JgyUtils.getInstance().checkAppPlatform() == JgyUtils.G10PPlatform || JgyUtils.getInstance().checkAppPlatform() == JgyUtils.C2Platform || JgyUtils.getInstance().checkAppPlatform() == JgyUtils.YXPD1Platform || JgyUtils.getInstance().checkAppPlatform() == JgyUtils.G11Platform || JgyUtils.getInstance().checkAppPlatform() == JgyUtils.MT8768Platform || JgyUtils.getInstance().checkAppPlatform() == JgyUtils.AUDG104Platform || JgyUtils.getInstance().checkAppPlatform() == JgyUtils.HL500Platform || JgyUtils.getInstance().checkAppPlatform() == JgyUtils.G11JPlatform || JgyUtils.getInstance().checkAppPlatform() == JgyUtils.P50Platform || JgyUtils.getInstance().checkAppPlatform() == JgyUtils.seewoPlatform || JgyUtils.getInstance().checkAppPlatform() == JgyUtils.U1302Platform || JgyUtils.getInstance().checkAppPlatform() == JgyUtils.MT6765Platform || JgyUtils.getInstance().checkAppPlatform() == JgyUtils.G128TPlatform || JgyUtils.getInstance().checkAppPlatform() == JgyUtils.QualcommTPlatform || JgyUtils.getInstance().checkAppPlatform() == JgyUtils.DX11Platform ) { return Utils.getProperty("ro.build.display.id", "获取失败"); } else { return Utils.getProperty("ro.custom.build.version", "获取失败"); } } /** * 获取系统版本号 * * @return */ public static String getRomVersion() { if (JgyUtils.getInstance().checkAppPlatform() == JgyUtils.ZhanruiPlatform) { return getProperty("ro.build.id", "获取失败"); } // else if (JgyUtils.getInstance().checkAppPlatform() == JgyUtils.CubePlatform) { // return Utils.getProperty("ro.build.id", "获取失败"); // } else if (JgyUtils.getInstance().checkAppPlatform() == JgyUtils.MTKPlatform) { return Utils.getProperty("ro.build.id", "获取失败"); } else { return getProperty("ro.build.display.id", "获取失败"); } } /** * 获取本机IP * * @param context * @return */ public static String getIPAddress(Context context) { ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);//获取系统的连接服务 NetworkInfo mActiveNetInfo = mConnectivityManager.getActiveNetworkInfo();//获取网络连接的信息 NetworkInfo info = mConnectivityManager.getActiveNetworkInfo(); if (info != null && info.isConnected()) { if ((info.getType() == ConnectivityManager.TYPE_MOBILE) || (info.getType() == ConnectivityManager.TYPE_WIFI)) {//当前使用2G/3G/4G网络 try { for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface intf = en.nextElement(); for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) { return inetAddress.getHostAddress(); } } } } catch (SocketException e) { e.printStackTrace(); } } } else { //当前无网络连接,请在设置中打开网络 return "网络未连接"; } return "获取失败"; } /** * 获取WiFi信号强度 * * @param context * @return */ public static int obtainWifiInfo(Context context) { // Wifi的连接速度及信号强度: WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE); // WifiInfo wifiInfo = wifiManager.getConnectionInfo(); WifiInfo info = wifiManager.getConnectionInfo(); if (info.getBSSID() != null) { // 链接信号强度 int strength = WifiManager.calculateSignalLevel(info.getRssi(), 5); // 链接速度 int speed = info.getLinkSpeed(); // 链接速度单位 String units = WifiInfo.LINK_SPEED_UNITS; // Wifi源名称 String ssid = info.getSSID(); int RSSI = info.getRssi(); return RSSI; } else { return 0; } } public static boolean isWifiAvailable(Context context) { ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo.State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState(); if (NetworkInfo.State.CONNECTED == wifi) { return true; } else { return false; } } 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(); } } public static String getBluetoothList(Context context) { BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); // 获取所有通过 GATT 连接的设备(适用于低功耗蓝牙 BLE) List connectedDevices = bluetoothManager.getConnectedDevices(BluetoothProfile.GATT); for (BluetoothDevice device : connectedDevices) { String deviceName = device.getName(); // 获取设备名称 String deviceAddress = device.getAddress(); // 获取 MAC 地址 Log.e("getBluetoothList", "已连接设备: " + deviceName + "(" + deviceAddress + ")"); } BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) { return "没有蓝牙设备"; } else { Log.e(TAG, "getBluetoothList: getName = " + bluetoothAdapter.getName()); //判断蓝牙设备是否已开起 if (!bluetoothAdapter.isEnabled()) { return "蓝牙未开启"; // //开起蓝牙设备 // Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // context.startActivity(intent); } else { Set devices = bluetoothAdapter.getBondedDevices(); StringBuilder stringBuilder = new StringBuilder(); for (Iterator iterator = devices.iterator(); iterator.hasNext(); ) { BluetoothDevice device = iterator.next(); if (device.isConnected()) { stringBuilder.append(device.getAlias()).append(";"); } } Log.e(TAG, "getConnectedBluetoothList: " + stringBuilder.toString()); return stringBuilder.toString(); } } } /** * 当前充电电流 mA *

* adb shell "cat /sys/class/power_supply/battery/BatteryAverageCurrent" */ public static int getCurrentChargingCurrent() { int result = 0; BufferedReader br = null; try { String line; br = new BufferedReader(new FileReader("/sys/class/power_supply/battery/BatteryAverageCurrent")); if ((line = br.readLine()) != null) { result = Integer.parseInt(line); } br.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } /** * 当前充电电压 uV *

* adb shell "cat /sys/class/power_supply/battery/batt_vol" */ public static int getCurrentChargingVoltage() { int result = 0; BufferedReader br = null; try { String line; br = new BufferedReader(new FileReader("/sys/class/power_supply/battery/batt_vol")); if ((line = br.readLine()) != null) { result = Integer.parseInt(line); } br.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } public static String getCacheDir(Context context) { String cachePath; if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) { if (context.getExternalCacheDir() != null) { cachePath = context.getExternalCacheDir().getPath(); } else if (context.getExternalFilesDir("cache") != null) { cachePath = context.getExternalFilesDir("cache").getPath(); } else { cachePath = context.getCacheDir().getPath(); } } else { cachePath = context.getCacheDir().getPath(); } return cachePath; } }