• 在开发app中很多时候需要获取设备的基本信息等运用到项目中,就需要一些方法获取,网上资源中方法五花八门,有的还获取不到,令人头大,话不多说,鄙人整理了一套方法,话不多说真机测试如下》上图:
  • 接下来就是代码片段了
  • 第一步接口方法类:DeviceUtils调用方法:DeviceUtils deviceUtils=new DeviceUtils(this);//实例化
  • 方法调用介绍
  • // LogTools.e(“获取设备手机制造商:”+ deviceUtils.getManufacturer());
    // LogTools.e(“获取设备AndroidID:”+deviceUtils.getAndroidID());
    // LogTools.e(“获取设备型号:”+deviceUtils.getModel());
    // LogTools.e(“获取唯一设备 ID:”+deviceUtils.getUniqueDeviceId());
    // LogTools.e(“获取设备 AppVersionCode:”+deviceUtils.getVersionCode());
    // LogTools.e(“获取唯一设备 AppVersionName:”+deviceUtils.getVerName());
    // LogTools.e(“获取设备系统版本号:”+ deviceUtils.getSDKVersionName());
    // LogTools.e(“获取设备系统版本码:”+deviceUtils.getSDKVersionCode());
    接下来就只需要傻瓜式复制粘贴就好
public class DeviceUtils {private static  Activity activity;public DeviceUtils(Activity activity) {this.activity=activity;}public static int getVersionCode() {int versionCode = 0;try {//获取软件版本号,对应AndroidManifest.xml下android:versionCodeversionCode = activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0).versionCode;} catch (PackageManager.NameNotFoundException e) {e.printStackTrace();}return versionCode;}/*** 获取版本号名称** @param* @return*/public static String getVerName() {String verName = "";try {verName = activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0).versionName;} catch (PackageManager.NameNotFoundException e) {e.printStackTrace();}return verName;}/*** Return the version name of device's system.** @return the version name of device's system*/public static String getSDKVersionName() {return Build.VERSION.RELEASE;}/*** Return version code of device's system.** @return version code of device's system*/public static int getSDKVersionCode() {return Build.VERSION.SDK_INT;}/*** Return the android id of device.** @return the android id of device*/@SuppressLint("HardwareIds")public static String getAndroidID() {String id = Settings.Secure.getString(activity.getContentResolver(),Settings.Secure.ANDROID_ID);if ("9774d56d682e549c".equals(id)) return "";return id == null ? "" : id;}/*** Return the manufacturer of the product/hardware.* <p>e.g. Xiaomi</p>** @return the manufacturer of the product/hardware*/public static String getManufacturer() {return Build.MANUFACTURER;}/*** Return the model of device.* <p>e.g. MI2SC</p>** @return the model of device*/public static String getModel() {String model = Build.MODEL;if (model != null) {model = model.trim().replaceAll("\\s*", "");} else {model = "";}return model;}/*** Return an ordered list of ABIs supported by this device. The most preferred ABI is the first* element in the list.** @return an ordered list of ABIs supported by this device*/public static String[] getABIs() {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {return Build.SUPPORTED_ABIS;} else {if (!TextUtils.isEmpty(Build.CPU_ABI2)) {return new String[]{Build.CPU_ABI, Build.CPU_ABI2};}return new String[]{Build.CPU_ABI};}}private static final    String KEY_UDID = "KEY_UDID";private volatile static String udid;/*** Return the unique device id.* <pre>{1}{UUID(macAddress)}</pre>* <pre>{2}{UUID(androidId )}</pre>* <pre>{9}{UUID(random    )}</pre>** @return the unique device id*/public static String getUniqueDeviceId() {return getUniqueDeviceId("", true);}/*** Return the unique device id.* <pre>android 10 deprecated {prefix}{1}{UUID(macAddress)}</pre>* <pre>{prefix}{2}{UUID(androidId )}</pre>* <pre>{prefix}{9}{UUID(random    )}</pre>** @param prefix The prefix of the unique device id.* @return the unique device id*/public static String getUniqueDeviceId(String prefix) {return getUniqueDeviceId(prefix, true);}/*** Return the unique device id.* <pre>{1}{UUID(macAddress)}</pre>* <pre>{2}{UUID(androidId )}</pre>* <pre>{9}{UUID(random    )}</pre>** @param useCache True to use cache, false otherwise.* @return the unique device id*/public static String getUniqueDeviceId(boolean useCache) {return getUniqueDeviceId("", useCache);}/*** Return the unique device id.* <pre>android 10 deprecated {prefix}{1}{UUID(macAddress)}</pre>* <pre>{prefix}{2}{UUID(androidId )}</pre>* <pre>{prefix}{9}{UUID(random    )}</pre>** @param prefix   The prefix of the unique device id.* @param useCache True to use cache, false otherwise.* @return the unique device id*/public static String getUniqueDeviceId(String prefix, boolean useCache) {if (!useCache) {return getUniqueDeviceIdReal(prefix);}if (udid == null) {synchronized (DeviceUtils.class) {if (udid == null) {UtilsBridge utilsBridge=new UtilsBridge(activity);final String id = utilsBridge.getSpUtils4Utils().getString(KEY_UDID, null);if (id != null) {udid = id;return udid;}return getUniqueDeviceIdReal(prefix);}}}return udid;}private static String getUniqueDeviceIdReal(String prefix) {try {final String androidId = getAndroidID();if (!TextUtils.isEmpty(androidId)) {return saveUdid(prefix + 2, androidId);}} catch (Exception ignore) {/**/}return saveUdid(prefix + 9, "");}private static String saveUdid(String prefix, String id) {udid = getUdid(prefix, id);UtilsBridge utilsBridge=new UtilsBridge(activity);utilsBridge.getSpUtils4Utils().put(KEY_UDID, udid);return udid;}private static String getUdid(String prefix, String id) {if (id.equals("")) {return prefix + UUID.randomUUID().toString().replace("-", "");}return prefix + UUID.nameUUIDFromBytes(id.getBytes()).toString().replace("-", "");}
}
public  class AdaptScreenUtils {private static List<Field> sMetricsFields;private AdaptScreenUtils() {throw new UnsupportedOperationException("u can't instantiate me...");}private static void applyDisplayMetrics(@NonNull final Resources resources, final float newXdpi) {resources.getDisplayMetrics().xdpi = newXdpi;Utils.getApp().getResources().getDisplayMetrics().xdpi = newXdpi;applyOtherDisplayMetrics(resources, newXdpi);}static Runnable getPreLoadRunnable() {return new Runnable() {@Overridepublic void run() {preLoad();}};}private static void preLoad() {applyDisplayMetrics(Resources.getSystem(), Resources.getSystem().getDisplayMetrics().xdpi);}private static void applyOtherDisplayMetrics(final Resources resources, final float newXdpi) {if (sMetricsFields == null) {sMetricsFields = new ArrayList<>();Class resCls = resources.getClass();Field[] declaredFields = resCls.getDeclaredFields();while (declaredFields != null && declaredFields.length > 0) {for (Field field : declaredFields) {if (field.getType().isAssignableFrom(DisplayMetrics.class)) {field.setAccessible(true);DisplayMetrics tmpDm = getMetricsFromField(resources, field);if (tmpDm != null) {sMetricsFields.add(field);tmpDm.xdpi = newXdpi;}}}resCls = resCls.getSuperclass();if (resCls != null) {declaredFields = resCls.getDeclaredFields();} else {break;}}} else {applyMetricsFields(resources, newXdpi);}}private static void applyMetricsFields(final Resources resources, final float newXdpi) {for (Field metricsField : sMetricsFields) {try {DisplayMetrics dm = (DisplayMetrics) metricsField.get(resources);if (dm != null) dm.xdpi = newXdpi;} catch (Exception e) {e.printStackTrace();}}}private static DisplayMetrics getMetricsFromField(final Resources resources, final Field field) {try {return (DisplayMetrics) field.get(resources);} catch (Exception ignore) {return null;}}
}
@SuppressLint("ApplySharedPref")
public  class SPUtils {Activity activity;public SPUtils(Activity activity) {this. activity=activity;}private static final Map<String, SPUtils> SP_UTILS_MAP = new HashMap<>();private SharedPreferences sp;public static SPUtils getInstance(String spName) {return getInstance(spName, Context.MODE_PRIVATE);}public static SPUtils getInstance(String spName, final int mode) {if (isSpace(spName)) spName = "spUtils";SPUtils spUtils = SP_UTILS_MAP.get(spName);if (spUtils == null) {synchronized (SPUtils.class) {spUtils = SP_UTILS_MAP.get(spName);if (spUtils == null) {spUtils = new SPUtils(spName, mode);SP_UTILS_MAP.put(spName, spUtils);}}}return spUtils;}private SPUtils(final String spName, final int mode) {sp = Utils.getApp().getSharedPreferences(spName, mode);}/*** Put the string value in sp.** @param key   The key of sp.* @param value The value of sp.*/public void put(@NonNull final String key, final String value) {put(key, value, false);}/*** Put the string value in sp.** @param key      The key of sp.* @param value    The value of sp.* @param isCommit True to use {@link SharedPreferences.Editor#commit()},*                 false to use {@link SharedPreferences.Editor#apply()}*/public void put(@NonNull final String key, final String value, final boolean isCommit) {if (isCommit) {sp.edit().putString(key, value).commit();} else {sp.edit().putString(key, value).apply();}}/*** Return the string value in sp.** @param key The key of sp.* @return the string value if sp exists or {@code ""} otherwise*/public String getString(@NonNull final String key) {return getString(key, "");}/*** Return the string value in sp.** @param key          The key of sp.* @param defaultValue The default value if the sp doesn't exist.* @return the string value if sp exists or {@code defaultValue} otherwise*/public String getString(@NonNull final String key, final String defaultValue) {return sp.getString(key, defaultValue);}/*** Put the int value in sp.** @param key   The key of sp.* @param value The value of sp.*/public void put(@NonNull final String key, final int value) {put(key, value, false);}/*** Put the int value in sp.** @param key      The key of sp.* @param value    The value of sp.* @param isCommit True to use {@link SharedPreferences.Editor#commit()},*                 false to use {@link SharedPreferences.Editor#apply()}*/public void put(@NonNull final String key, final int value, final boolean isCommit) {if (isCommit) {sp.edit().putInt(key, value).commit();} else {sp.edit().putInt(key, value).apply();}}/*** Return the int value in sp.** @param key The key of sp.* @return the int value if sp exists or {@code -1} otherwise*/public int getInt(@NonNull final String key) {return getInt(key, -1);}/*** Return the int value in sp.** @param key          The key of sp.* @param defaultValue The default value if the sp doesn't exist.* @return the int value if sp exists or {@code defaultValue} otherwise*/public int getInt(@NonNull final String key, final int defaultValue) {return sp.getInt(key, defaultValue);}/*** Put the long value in sp.** @param key   The key of sp.* @param value The value of sp.*/public void put(@NonNull final String key, final long value) {put(key, value, false);}/*** Put the long value in sp.** @param key      The key of sp.* @param value    The value of sp.* @param isCommit True to use {@link SharedPreferences.Editor#commit()},*                 false to use {@link SharedPreferences.Editor#apply()}*/public void put(@NonNull final String key, final long value, final boolean isCommit) {if (isCommit) {sp.edit().putLong(key, value).commit();} else {sp.edit().putLong(key, value).apply();}}/*** Return the long value in sp.** @param key The key of sp.* @return the long value if sp exists or {@code -1} otherwise*/public long getLong(@NonNull final String key) {return getLong(key, -1L);}/*** Return the long value in sp.** @param key          The key of sp.* @param defaultValue The default value if the sp doesn't exist.* @return the long value if sp exists or {@code defaultValue} otherwise*/public long getLong(@NonNull final String key, final long defaultValue) {return sp.getLong(key, defaultValue);}/*** Put the float value in sp.** @param key   The key of sp.* @param value The value of sp.*/public void put(@NonNull final String key, final float value) {put(key, value, false);}/*** Put the float value in sp.** @param key      The key of sp.* @param value    The value of sp.* @param isCommit True to use {@link SharedPreferences.Editor#commit()},*                 false to use {@link SharedPreferences.Editor#apply()}*/public void put(@NonNull final String key, final float value, final boolean isCommit) {if (isCommit) {sp.edit().putFloat(key, value).commit();} else {sp.edit().putFloat(key, value).apply();}}/*** Return the float value in sp.** @param key The key of sp.* @return the float value if sp exists or {@code -1f} otherwise*/public float getFloat(@NonNull final String key) {return getFloat(key, -1f);}/*** Return the float value in sp.** @param key          The key of sp.* @param defaultValue The default value if the sp doesn't exist.* @return the float value if sp exists or {@code defaultValue} otherwise*/public float getFloat(@NonNull final String key, final float defaultValue) {return sp.getFloat(key, defaultValue);}/*** Put the boolean value in sp.** @param key   The key of sp.* @param value The value of sp.*/public void put(@NonNull final String key, final boolean value) {put(key, value, false);}/*** Put the boolean value in sp.** @param key      The key of sp.* @param value    The value of sp.* @param isCommit True to use {@link SharedPreferences.Editor#commit()},*                 false to use {@link SharedPreferences.Editor#apply()}*/public void put(@NonNull final String key, final boolean value, final boolean isCommit) {if (isCommit) {sp.edit().putBoolean(key, value).commit();} else {sp.edit().putBoolean(key, value).apply();}}/*** Return the boolean value in sp.** @param key The key of sp.* @return the boolean value if sp exists or {@code false} otherwise*/public boolean getBoolean(@NonNull final String key) {return getBoolean(key, false);}/*** Return the boolean value in sp.** @param key          The key of sp.* @param defaultValue The default value if the sp doesn't exist.* @return the boolean value if sp exists or {@code defaultValue} otherwise*/public boolean getBoolean(@NonNull final String key, final boolean defaultValue) {return sp.getBoolean(key, defaultValue);}/*** Put the set of string value in sp.** @param key   The key of sp.* @param value The value of sp.*/public void put(@NonNull final String key, final Set<String> value) {put(key, value, false);}/*** Put the set of string value in sp.** @param key      The key of sp.* @param value    The value of sp.* @param isCommit True to use {@link SharedPreferences.Editor#commit()},*                 false to use {@link SharedPreferences.Editor#apply()}*/public void put(@NonNull final String key,final Set<String> value,final boolean isCommit) {if (isCommit) {sp.edit().putStringSet(key, value).commit();} else {sp.edit().putStringSet(key, value).apply();}}/*** Return the set of string value in sp.** @param key The key of sp.* @return the set of string value if sp exists* or {@code Collections.<String>emptySet()} otherwise*/public Set<String> getStringSet(@NonNull final String key) {return getStringSet(key, Collections.<String>emptySet());}/*** Return the set of string value in sp.** @param key          The key of sp.* @param defaultValue The default value if the sp doesn't exist.* @return the set of string value if sp exists or {@code defaultValue} otherwise*/public Set<String> getStringSet(@NonNull final String key,final Set<String> defaultValue) {return sp.getStringSet(key, defaultValue);}/*** Return all values in sp.** @return all values in sp*/public Map<String, ?> getAll() {return sp.getAll();}/*** Return whether the sp contains the preference.** @param key The key of sp.* @return {@code true}: yes<br>{@code false}: no*/public boolean contains(@NonNull final String key) {return sp.contains(key);}/*** Remove the preference in sp.** @param key The key of sp.*/public void remove(@NonNull final String key) {remove(key, false);}/*** Remove the preference in sp.** @param key      The key of sp.* @param isCommit True to use {@link SharedPreferences.Editor#commit()},*                 false to use {@link SharedPreferences.Editor#apply()}*/public void remove(@NonNull final String key, final boolean isCommit) {if (isCommit) {sp.edit().remove(key).commit();} else {sp.edit().remove(key).apply();}}/*** Remove all preferences in sp.*/public void clear() {clear(false);}/*** Remove all preferences in sp.** @param isCommit True to use {@link SharedPreferences.Editor#commit()},*                 false to use {@link SharedPreferences.Editor#apply()}*/public void clear(final boolean isCommit) {if (isCommit) {sp.edit().clear().commit();} else {sp.edit().clear().apply();}}private static boolean isSpace(final String s) {if (s == null) return true;for (int i = 0, len = s.length(); i < len; ++i) {if (!Character.isWhitespace(s.charAt(i))) {return false;}}return true;}
}
public class ThreadUtils {private static final Map<Integer, Map<Integer, ExecutorService>> TYPE_PRIORITY_POOLS = new HashMap<>();private static final int   CPU_COUNT = Runtime.getRuntime().availableProcessors();private static final byte TYPE_SINGLE = -1;private static final byte TYPE_CACHED = -2;private static final byte TYPE_IO     = -4;private static final byte TYPE_CPU    = -8;public static ExecutorService getCachedPool() {return getPoolByTypeAndPriority(TYPE_CACHED);}private static ExecutorService getPoolByTypeAndPriority(final int type) {return getPoolByTypeAndPriority(type, Thread.NORM_PRIORITY);}private static ExecutorService getPoolByTypeAndPriority(final int type, final int priority) {synchronized (TYPE_PRIORITY_POOLS) {ExecutorService pool;Map<Integer, ExecutorService> priorityPools = TYPE_PRIORITY_POOLS.get(type);if (priorityPools == null) {priorityPools = new ConcurrentHashMap<>();pool = ThreadPoolExecutor4Util.createPool(type, priority);priorityPools.put(priority, pool);TYPE_PRIORITY_POOLS.put(type, priorityPools);} else {pool = priorityPools.get(priority);if (pool == null) {pool = ThreadPoolExecutor4Util.createPool(type, priority);priorityPools.put(priority, pool);}}return pool;}}static final class ThreadPoolExecutor4Util extends ThreadPoolExecutor {private static ExecutorService createPool(final int type, final int priority) {switch (type) {case TYPE_SINGLE:return new ThreadPoolExecutor4Util(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue4Util(),new UtilsThreadFactory("single", priority));case TYPE_CACHED:return new ThreadPoolExecutor4Util(0, 128,60L, TimeUnit.SECONDS,new LinkedBlockingQueue4Util(true),new UtilsThreadFactory("cached", priority));case TYPE_IO:return new ThreadPoolExecutor4Util(2 * CPU_COUNT + 1, 2 * CPU_COUNT + 1,30, TimeUnit.SECONDS,new LinkedBlockingQueue4Util(),new UtilsThreadFactory("io", priority));case TYPE_CPU:return new ThreadPoolExecutor4Util(CPU_COUNT + 1, 2 * CPU_COUNT + 1,30, TimeUnit.SECONDS,new LinkedBlockingQueue4Util(true),new UtilsThreadFactory("cpu", priority));default:return new ThreadPoolExecutor4Util(type, type,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue4Util(),new UtilsThreadFactory("fixed(" + type + ")", priority));}}private final AtomicInteger mSubmittedCount = new AtomicInteger();private LinkedBlockingQueue4Util mWorkQueue;ThreadPoolExecutor4Util(int corePoolSize, int maximumPoolSize,long keepAliveTime, TimeUnit unit,LinkedBlockingQueue4Util workQueue,ThreadFactory threadFactory) {super(corePoolSize, maximumPoolSize,keepAliveTime, unit,workQueue,threadFactory);workQueue.mPool = this;mWorkQueue = workQueue;}private int getSubmittedCount() {return mSubmittedCount.get();}@Overrideprotected void afterExecute(Runnable r, Throwable t) {mSubmittedCount.decrementAndGet();super.afterExecute(r, t);}@Overridepublic void execute(@NonNull Runnable command) {if (this.isShutdown()) return;mSubmittedCount.incrementAndGet();try {super.execute(command);} catch (RejectedExecutionException ignore) {Log.e("ThreadUtils", "This will not happen!");mWorkQueue.offer(command);} catch (Throwable t) {mSubmittedCount.decrementAndGet();}}}private static final class LinkedBlockingQueue4Util extends LinkedBlockingQueue<Runnable> {private volatile ThreadPoolExecutor4Util mPool;private int mCapacity = Integer.MAX_VALUE;LinkedBlockingQueue4Util() {super();}LinkedBlockingQueue4Util(boolean isAddSubThreadFirstThenAddQueue) {super();if (isAddSubThreadFirstThenAddQueue) {mCapacity = 0;}}LinkedBlockingQueue4Util(int capacity) {super();mCapacity = capacity;}@Overridepublic boolean offer(@NonNull Runnable runnable) {if (mCapacity <= size() &&mPool != null && mPool.getPoolSize() < mPool.getMaximumPoolSize()) {// create a non-core threadreturn false;}return super.offer(runnable);}}static final class UtilsThreadFactory extends AtomicLongimplements ThreadFactory {private static final AtomicInteger POOL_NUMBER      = new AtomicInteger(1);private static final long          serialVersionUID = -9209200509960368598L;private final        String        namePrefix;private final        int           priority;private final        boolean       isDaemon;UtilsThreadFactory(String prefix, int priority) {this(prefix, priority, false);}UtilsThreadFactory(String prefix, int priority, boolean isDaemon) {namePrefix = prefix + "-pool-" +POOL_NUMBER.getAndIncrement() +"-thread-";this.priority = priority;this.isDaemon = isDaemon;}@Overridepublic Thread newThread(@NonNull Runnable r) {Thread t = new Thread(r, namePrefix + getAndIncrement()) {@Overridepublic void run() {try {super.run();} catch (Throwable t) {Log.e("ThreadUtils", "Request threw uncaught throwable", t);}}};t.setDaemon(isDaemon);t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {@Overridepublic void uncaughtException(Thread t, Throwable e) {System.out.println(e);}});t.setPriority(priority);return t;}}}
public  class Utils {@SuppressLint("StaticFieldLeak")private static Application sApp;private Utils() {throw new UnsupportedOperationException("u can't instantiate me...");}/*** Init utils.* <p>Init it in the class of UtilsFileProvider.</p>** @param app application*/public static void init(final Application app) {if (app == null) {Log.e("Utils", "app is null.");return;}if (sApp == null) {sApp = app;UtilsBridge.init(sApp);UtilsBridge.preLoad();return;}if (sApp.equals(app)) return;UtilsBridge.unInit(sApp);sApp = app;UtilsBridge.init(sApp);}/*** Return the Application object.* <p>Main process get app by UtilsFileProvider,* and other process get app by reflect.</p>** @return the Application object*/public static Application getApp() {if (sApp != null) return sApp;init(UtilsBridge.getApplicationByReflect());if (sApp == null) throw new NullPointerException("reflect failed.");return sApp;}///// interface///public interface OnAppStatusChangedListener {void onForeground(Activity activity);void onBackground(Activity activity);}public static class ActivityLifecycleCallbacks {public void onActivityCreated(@NonNull Activity activity) {/**/}public void onActivityStarted(@NonNull Activity activity) {/**/}public void onActivityResumed(@NonNull Activity activity) {/**/}public void onActivityPaused(@NonNull Activity activity) {/**/}public void onActivityStopped(@NonNull Activity activity) {/**/}public void onActivityDestroyed(@NonNull Activity activity) {/**/}public void onLifecycleChanged(@NonNull Activity activity, Lifecycle.Event event) {/**/}}public interface Consumer<T> {void accept(T t);}public interface Supplier<T> {T get();}public interface Func1<Ret, Par> {Ret call(Par param);}
}
class UtilsActivityLifecycleImpl implements Application.ActivityLifecycleCallbacks {static final UtilsActivityLifecycleImpl INSTANCE = new UtilsActivityLifecycleImpl();private final LinkedList<Activity> mActivityList = new LinkedList<>();void init(Application app) {app.registerActivityLifecycleCallbacks(this);}void unInit(Application app) {mActivityList.clear();app.unregisterActivityLifecycleCallbacks(this);}@Overridepublic void onActivityCreated(@NonNull Activity activity, @Nullable Bundle bundle) {}@Overridepublic void onActivityStarted(@NonNull Activity activity) {}@Overridepublic void onActivityResumed(@NonNull Activity activity) {}@Overridepublic void onActivityPaused(@NonNull Activity activity) {}@Overridepublic void onActivityStopped(@NonNull Activity activity) {}@Overridepublic void onActivityPostStopped(@NonNull Activity activity) {/**/}@Overridepublic void onActivityPreSaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {/**/}@Overridepublic void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {/**/}@Overridepublic void onActivityPostSaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {/**/}@Overridepublic void onActivityPreDestroyed(@NonNull Activity activity) {/**/}@Overridepublic void onActivityDestroyed(@NonNull Activity activity) {}Application getApplicationByReflect() {try {Class activityThreadClass = Class.forName("android.app.ActivityThread");Object thread = getActivityThread();if (thread == null) return null;Object app = activityThreadClass.getMethod("getApplication").invoke(thread);if (app == null) return null;return (Application) app;} catch (Exception e) {e.printStackTrace();}return null;}private Object getActivityThread() {Object activityThread = getActivityThreadInActivityThreadStaticField();if (activityThread != null) return activityThread;return getActivityThreadInActivityThreadStaticMethod();}private Object getActivityThreadInActivityThreadStaticField() {try {Class activityThreadClass = Class.forName("android.app.ActivityThread");Field sCurrentActivityThreadField = activityThreadClass.getDeclaredField("sCurrentActivityThread");sCurrentActivityThreadField.setAccessible(true);return sCurrentActivityThreadField.get(null);} catch (Exception e) {Log.e("UtilsActivityLifecycle", "getActivityThreadInActivityThreadStaticField: " + e.getMessage());return null;}}private Object getActivityThreadInActivityThreadStaticMethod() {try {Class activityThreadClass = Class.forName("android.app.ActivityThread");return activityThreadClass.getMethod("currentActivityThread").invoke(null);} catch (Exception e) {Log.e("UtilsActivityLifecycle", "getActivityThreadInActivityThreadStaticMethod: " + e.getMessage());return null;}}
}
public class UtilsBridge {private  static Activity activity;public UtilsBridge(Activity activity) {this. activity=activity;}static void init(Application app) {UtilsActivityLifecycleImpl.INSTANCE.init(app);}static void unInit(Application app) {UtilsActivityLifecycleImpl.INSTANCE.unInit(app);}static void preLoad() {preLoad(AdaptScreenUtils.getPreLoadRunnable());}private static void preLoad(final Runnable... runs) {for (final Runnable r : runs) {ThreadUtils.getCachedPool().execute(r);}}static SPUtils getSpUtils4Utils() {SPUtils spUtils=new SPUtils(activity);return spUtils.getInstance("Utils");}static Application getApplicationByReflect() {return UtilsActivityLifecycleImpl.INSTANCE.getApplicationByReflect();}}

不需要懂,不懂也不要问我谢谢!!!

Android专业获取设备信息如:AndroidID、唯一设备ID、制造商、型号、版本号、版本码等相关推荐

  1. Android中获取屏幕信息的几种方式

    Android中获取屏幕信息的几种方式 方案一 方案二 方案三 Note:以下方案中的this均指Activity. 方案一 WindowManager wm = (WindowManager) th ...

  2. android手机获取cpu信息

    前言 获取android手机的设备信息,首先要从android手机系统的所基于的linux的入手. 通过调试桥获取cpu信息 当然使用linux桌面的用户通过命令:cat /proc/cpuinfo ...

  3. Android Studio 获取磁盘信息获取imei

    到AndroidManifest.xml文件设置权限: <?xml version="1.0" encoding="utf-8"?> <man ...

  4. android手机系统检测工具下载,手机设备信息检测软件下载-设备信息检测appv1.0 官方版-腾牛安卓网...

    设备信息检测app,一款好用的手机测评工具.软件支持硬件信息.系统信息.CPU.GPU以及手机内存等信息查询检测,帮助全方位了解手机性能. 官方简介: 设备信息检测软件是一款对手机基本信息的查看包括硬 ...

  5. android GPS 获取城市信息

    1.取得用户当前位置的经度,纬度. 2.根据经纬度转换成城市名称. 取得用户当前位置的经度,纬度 今天弄了一个多小时,写了一个GPS获取地理位置代码的小例子,包括参考了网上的一些代码,并且对代码进行了 ...

  6. 对Android GPS获取位置信息的新研究.

    前段时间略看了Android 的GPS API,就冒然发布了一片博文,现在再回过头来看看,确实有不少不足甚至错误.这篇算做补充和纠正吧. 1.要想获取位置信息,需要在手机设置中将"位置与安全 ...

  7. 【Android Studio安装部署系列】十一、Android studio获取数字签名信息

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 概述 下面介绍下调试版本和发布版本获取数字签名的方法,通过以下方法可以获取到SHA1和MD5. 一般在使用分享功能,在第三方平台中创建应用 ...

  8. c#使用WPD读取便携式设备信息一(枚举设备、连接设备及读取设备信息)

    手机或其他电子设备通过USB插入电脑上,并且以MTP(媒体传输协议)方式连接时,可在"计算机"中看到类似计算机盘符的便携式设备文件夹显示,但是这并不是一个计算机盘符,并不能通过常规 ...

  9. Android Build 获取手机信息

    1.什么是Android属性? 属性(property)系统对Android来说是一个重要的功能.他作为一个系统服务管理着系统的配置和状态,所有的这些系统配置和状态都是属性(property).属性( ...

最新文章

  1. 在Spring MVC中处理域对象
  2. AUTOSAR从入门到精通100讲(118)-深度解析自动驾驶主流芯片及平台架构
  3. 提出建议Do you want to..._44
  4. 单、双链表的循环链表(十五)
  5. js 设置 Cookie,cookie的作用域设置
  6. BOS物流项目02———创建项目
  7. iframe 防止挂马的问题
  8. Matlab在线运行网站
  9. RTSP/Onvif视频智能平台EasyNVR播放视频卡顿的原因分析及解决
  10. 黑马程序员--java简介
  11. 马丁富勒微服务论文连接
  12. 西部世界:人的大部分痛苦来自控制一切的执念
  13. python编程<十五>
  14. Python:用【Win32】模块,结合Word通配符替换,将Word文档表格的部分内容替换为加粗
  15. vue实现就诊人信息的增删改查
  16. js密码输入与确认密码验证功能
  17. 深度学习:算法到实战
  18. 【概率论】几种常见的概率分布表
  19. 我发现凡是给offer的公司,面试时基本不问技术细节,那些问得又多又细的公司,后面就没下文了!...
  20. python数组长度查询_python – 在numpy数组中查找相同值的序列长度(运行长度编码)...

热门文章

  1. 神奇电子计算机 教学设计,大连理工版三年级下册信息技术 7. 神奇的艺术字 教案...
  2. NNDL 作业4:第四章课后题
  3. 一球成谜!咪咕直播联合即构打造世界杯直播答题新玩法
  4. [小说]魔王冢(35)天目
  5. 原生JS【fiveKeyPress】2秒内五次点击键盘任意键(或组合键)触发自定义事件(以Pause/Break键为例)
  6. 大学生php实训总结_php实训报告心得体会
  7. 去哪儿PMO Head赵云:项目管理背后有哪些生存之道?
  8. OSPF特殊区域及其他特性
  9. Springboot轻松整合Mybatis
  10. 大厂程序员完美的一天