Android TV 开发需要用到的一些功能源码

此文大部分内容为转发,但作为开发Android TV的重要部分,也还是转发一下,省的读者到处找。

包括:设备、存储、内存、网络、蓝牙等

1 设备基本信息获取

import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import android.os.Build; import android.util.Log; public class BuildHelper { private static final String TAG = BuildHelper.class.getSimpleName(); /** * Build class所有的字段属性 * Build.BOARD : Z91 * Build.BOOTLOADER : unknown * Build.BRAND : FaDi * Build.CPU_ABI : arm64-v8a * Build.CPU_ABI2 : * Build.DEVICE : Z91 * Build.DISPLAY : TEST_FaDi_Z91_S100_20180108 * Build.FINGERPRINT : FaDi/Z91/Z91:7.1.1/N6F26Q/1515397384:user/release-keys * Build.HARDWARE : mt6739 * Build.HOST : 69959bbb90c6 * Build.ID : N6F26Q * Build.IS_DEBUGGABLE : true * Build.IS_EMULATOR : false * Build.MANUFACTURER : FaDi * Build.MODEL : Z91 * Build.PERMISSIONS_REVIEW_REQUIRED : false * Build.PRODUCT : Z91 * Build.RADIO : unknown * Build.SERIAL : 0123456789ABCDEF * Build.SUPPORTED_32_BIT_ABIS : [Ljava.lang.String;@305cf5e * Build.SUPPORTED_64_BIT_ABIS : [Ljava.lang.String;@f5c1f3f * Build.SUPPORTED_ABIS : [Ljava.lang.String;@578b00c * Build.TAG : Build * Build.TAGS : release-keys * Build.TIME : 1515397382000 * Build.TYPE : user * Build.UNKNOWN : unknown * Build.USER : FaDi * Build.VERSION.ACTIVE_CODENAMES : [Ljava.lang.String;@f4ecd55 * Build.VERSION.ALL_CODENAMES : [Ljava.lang.String;@bdb836a * Build.VERSION.BASE_OS : * Build.VERSION.CODENAME : REL * Build.VERSION.INCREMENTAL : 1515397384 * Build.VERSION.PREVIEW_SDK_INT : 0 * Build.VERSION.RELEASE : 7.1.1 * Build.VERSION.RESOURCES_SDK_INT : 25 * Build.VERSION.SDK : 25 * Build.VERSION.SDK_INT : 25 * Build.VERSION.SECURITY_PATCH : 2017-11-05 */ public static List<String> getAllBuildInformation() { List<String> result = new ArrayList<>(); Field[] fields = Build.class.getDeclaredFields(); for (Field field : fields) { try { field.setAccessible(true); String info = “Build.” + field.getName() + ” : ” + field.get(null); Log.w(TAG, info); result.add(info); } catch (Exception e) { Log.e(TAG, “an error occured when collect crash info”, e); } } Field[] fieldsVersion = Build.VERSION.class.getDeclaredFields(); for (Field field : fieldsVersion) { try { field.setAccessible(true); String info = “Build.VERSION.” + field.getName() + ” : ” + field.get(null); Log.w(TAG, info); result.add(info); } catch (Exception e) { Log.e(TAG, “an error occured when collect crash info”, e); } } return result; } // 手机制造商 public static String getProduct() { return Build.PRODUCT; } // 系统定制商 public static String getBrand() { return Build.BRAND; } // 硬件制造商 public static String getManufacturer() { return Build.MANUFACTURER; } // 平台信息 public static String getHardWare() { String result = Build.HARDWARE; if (result.matches(“qcom”)) { Log.d(TAG, “Qualcomm platform”); result = “高通平台(Qualcomm) – ” + result; } else if (result.matches(“mt[0-9]*”)) { result = “MTK平台(MediaTek) – ” + result; } return result; } // 型号 public static String getMode() { return Build.MODEL; } // Android 系统版本 public static String getAndroidVersion() { return Build.VERSION.RELEASE; } // CPU 指令集,可以查看是否支持64位 public static String getCpuAbi() { return Build.CPU_ABI; } public static boolean isCpu64() { boolean result = false; if (Build.CPU_ABI.contains(“arm64”)) { result = true; } return result; } // 显示模块 public static String getDisplay() { return Build.DISPLAY; } // SDK 当前版本号 public static int getCurSDK() { return Build.VERSION.SDK_INT; } }

2 手机属性值获取

import android.os.Build; import android.util.Log; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * 属性文件 * /init.rc * <p/> * /default.prop * <p/> * /system/build.prop */ public class PropInfoUtil { private static final String TAG = PropInfoUtil.class.getSimpleName(); public static List<String> getPropInfo() { List<String> result = new ArrayList<>(); try { String line; BufferedReader br = new BufferedReader(new FileReader(“/default.prop”)); result.add(“*** Read From /default.prop ***”); while ((line = br.readLine()) != null) { result.add(line); } result.add(“*** Read From /system/build.prop ***”); br = new BufferedReader(new FileReader(“/system/build.prop”)); while ((line = br.readLine()) != null) { result.add(line); } /* (Permission denied) result.add(“*** Read From /init.rc ***”); Log.d(TAG, “*** Read From /init.rc ***”); br = new BufferedReader(new FileReader(“/init.rc”)); while ((line = br.readLine()) != null) { result.add(line); Log.d(TAG, line); } */ br.close(); } catch (IOException e) { e.printStackTrace(); } return result; } /** * Java VM 虚拟机 * * @return */ public static String getJavaVM() { String result = null; result = System.getProperty(“java.vm.name”); if (result != null) { result = result + System.getProperty(“java.vm.version”); } return result; } /** * 内核架构 * * @return */ public static String getKernelArchitecture() { return System.getProperty(“os.arch”); } /** * 内核版本 * * @return */ public static String getKernelVersion() { return System.getProperty(“os.version”) + ” (” + Build.VERSION.INCREMENTAL + “)”; } }

3 手机存储卡信息获取

import android.app.ActivityManager; import android.content.Context; import android.os.Environment; import android.os.StatFs; import android.text.TextUtils; import android.text.format.Formatter; import android.util.Log; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; public class SystemUtils { /** * OpenGL ES 版本 * * @param mContext * @return */ public static String getOpenGlVersion(Context mContext) { return ((ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE)).getDeviceConfigurationInfo().getGlEsVersion(); } /** * 获得SD卡总大小 * * @return */ public static String getSDTotalSize(Context mContext) { File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long totalBlocks = stat.getBlockCount(); return Formatter.formatFileSize(mContext, blockSize * totalBlocks); } /** * 获得sd卡剩余容量,即可用大小 * * @return */ public static String getSDAvailableSize(Context mContext) { File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); return Formatter.formatFileSize(mContext, blockSize * availableBlocks); } /** * 获得机身ROM总大小 * * @return */ public static String getRomTotalSize(Context mContext) { File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long totalBlocks = stat.getBlockCount(); return Formatter.formatFileSize(mContext, blockSize * totalBlocks); } /** * 获得机身可用ROM * * @return */ public static String getRomAvailableSize(Context mContext) { File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); return Formatter.formatFileSize(mContext, blockSize * availableBlocks); } public static boolean isRooted() { // nexus 5x “/su/bin/” String[] paths = {“/system/xbin/”, “/system/bin/”, “/system/sbin/”, “/sbin/”, “/vendor/bin/”, “/su/bin/”}; try { for (int i = 0; i < paths.length; i++) { String path = paths[i] + “su”; if (new File(path).exists()) { String execResult = exec(new String[]{“ls”, “-l”, path}); Log.d(“cyb”, “isRooted=” + execResult); if (TextUtils.isEmpty(execResult) || execResult.indexOf(“root”) == execResult.lastIndexOf(“root”)) { return false; } return true; } } } catch (Exception e) { e.printStackTrace(); } return false; } private static String exec(String[] exec) { String ret = “”; ProcessBuilder processBuilder = new ProcessBuilder(exec); try { Process process = processBuilder.start(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = bufferedReader.readLine()) != null) { ret += line; } process.getInputStream().close(); process.destroy(); } catch (Exception e) { e.printStackTrace(); } return ret; } }

4 屏幕信息获取

import android.app.Activity; import android.content.Context; import android.graphics.Point; import android.os.Build; import android.util.DisplayMetrics; import android.view.Display; import android.view.WindowManager; import com.fadisu.cpurun.R; import com.fadisu.cpurun.bean.ScreenInfo; public class ScreenUtil { // 将px值转换为dip或dp值,保证尺寸大小不变 public static int px2dip(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } // 将dip或dp值转换为px值,保证尺寸大小不变 public static int dip2px(Context context, float dipValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dipValue * scale + 0.5f); } // 将px值转换为sp值,保证文字大小不变 public static int px2sp(Context context, float pxValue) { final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; return (int) (pxValue / fontScale + 0.5f); } // 将sp值转换为px值,保证文字大小不变 public static int sp2px(Context context, float spValue) { final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; return (int) (spValue * fontScale + 0.5f); } // 屏幕宽度(像素) public static int getWindowWidth(Activity context) { DisplayMetrics metric = new DisplayMetrics(); context.getWindowManager().getDefaultDisplay().getMetrics(metric); return metric.widthPixels; } // 屏幕高度(像素) public static int getWindowHeight(Activity context) { DisplayMetrics metric = new DisplayMetrics(); context.getWindowManager().getDefaultDisplay().getMetrics(metric); return metric.heightPixels; } /** * 获得状态栏的高度 * * @param context * @return */ public static int getStatusHeight(Context context) { int statusHeight = -1; try { Class<?> clazz = Class.forName(“com.android.internal.R$dimen”); Object object = clazz.newInstance(); int height = Integer.parseInt(clazz.getField(“status_bar_height”) .get(object).toString()); statusHeight = context.getResources().getDimensionPixelSize(height); } catch (Exception e) { e.printStackTrace(); } return statusHeight; } /** * 屏幕分辨率 * * @param mContext * @return */ public static ScreenInfo getScreenInfo(Context mContext) { ScreenInfo result = new ScreenInfo(); int widthPixels; int heightPixels; WindowManager w = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); Display d = w.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); d.getMetrics(metrics); // since SDK_INT = 1; widthPixels = metrics.widthPixels; heightPixels = metrics.heightPixels; // includes window decorations (statusbar bar/menu bar) if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17) { try { widthPixels = (Integer) Display.class.getMethod(“getRawWidth”).invoke(d); heightPixels = (Integer) Display.class.getMethod(“getRawHeight”).invoke(d); } catch (Exception ignored) { ignored.printStackTrace(); } } // includes window decorations (statusbar bar/menu bar) if (Build.VERSION.SDK_INT >= 17) { try { Point realSize = new Point(); Display.class.getMethod(“getRealSize”, Point.class).invoke(d, realSize); widthPixels = realSize.x; heightPixels = realSize.y; } catch (Exception ignored) { ignored.printStackTrace(); } } result.widthPixels = widthPixels; result.heightPixels = heightPixels; result.screenRealMetrics = widthPixels + ” X ” + heightPixels; result.density = metrics.density; result.density_default = metrics.DENSITY_DEFAULT; result.densityDpi = metrics.densityDpi; result.densityDpiStr = metrics.densityDpi + ” dpi”; result.scaledDensity = metrics.scaledDensity; result.xdpi = metrics.xdpi; result.ydpi = metrics.ydpi; result.size = (Math.sqrt(Math.pow(widthPixels, 2) + Math.pow(heightPixels, 2)) / metrics.densityDpi); result.sizeStr = String.format(“%.2f”, result.size) + mContext.getResources().getString(R.string.sys_inches_unit); return result; } }

5 内存信息获取

import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MemInfoUtil { public static List<String> getMemInfo() { List<String> result = new ArrayList<>(); try { String line; BufferedReader br = new BufferedReader(new FileReader(“/proc/meminfo”)); while ((line = br.readLine()) != null) { result.add(line); } br.close(); } catch (IOException e) { e.printStackTrace(); } return result; } /* /proc/meminfo MemTotal: 2902436 kB MemFree: 199240 kB MemAvailable: 1088764 kB Buffers: 40848 kB Cached: 862908 kB SwapCached: 54696 kB Active: 1222848 kB Inactive: 671468 kB Active(anon): 758516 kB Inactive(anon): 242560 kB Active(file): 464332 kB Inactive(file): 428908 kB Unevictable: 5972 kB Mlocked: 256 kB SwapTotal: 1048572 kB SwapFree: 537124 kB Dirty: 12 kB Writeback: 0 kB AnonPages: 988820 kB Mapped: 508996 kB Shmem: 4800 kB Slab: 157204 kB SReclaimable: 57364 kB SUnreclaim: 99840 kB KernelStack: 41376 kB PageTables: 51820 kB NFS_Unstable: 0 kB Bounce: 0 kB WritebackTmp: 0 kB CommitLimit: 2499788 kB Committed_AS: 76292324 kB VmallocTotal: 258867136 kB VmallocUsed: 0 kB VmallocChunk: 0 kB CmaTotal: 0 kB CmaFree: 0 kB */ public static String getFieldFromMeminfo(String field) throws IOException { BufferedReader br = new BufferedReader(new FileReader(“/proc/meminfo”)); Pattern p = Pattern.compile(field + “\\s*:\\s*(.*)”); try { String line; while ((line = br.readLine()) != null) { Matcher m = p.matcher(line); if (m.matches()) { return m.group(1); } } } finally { br.close(); } return null; } public static String getMemTotal() { String result = null; try { result = getFieldFromMeminfo(“MemTotal”); } catch (IOException e) { e.printStackTrace(); } return result; } public static String getMemAvailable() { String result = null; try { result = getFieldFromMeminfo(“MemAvailable”); } catch (IOException e) { e.printStackTrace(); } return result; } }

6 检测网络链接

import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.provider.Settings; import android.util.Log; /** * 关于网络的判断和设置 */ public class NetworkUtils { /** 网络不可用 */ public static final int NO_NET_WORK = 0; /** 是wifi连接 */ public static final int WIFI = 1; /** 不是wifi连接 */ public static final int NO_WIFI = 2; private NetworkUtils(){ /* cannot be instantiated */ throw new UnsupportedOperationException(“cannot be instantiated”); } /** * 判断是否打开网络 * @param context * @return */ public static boolean isNetWorkAvailable(Context context){ boolean isAvailable = false ; ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); if(networkInfo!=null && networkInfo.isAvailable()){ isAvailable = true; } Log.d(“WIFI”,isAvailable+””); return isAvailable; } /** * 获取网络类型 * @param context * @return */ public static int getNetWorkType(Context context) { if (!isNetWorkAvailable(context)) { return NetworkUtils.NO_NET_WORK; } ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting()) return NetworkUtils.WIFI; else return NetworkUtils.NO_WIFI; } /** * 判断当前网络是否为wifi * @param context * @return 如果为wifi返回true;否则返回false */ @SuppressWarnings(“static-access”) public static boolean isWiFiConnected(Context context){ ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = manager.getActiveNetworkInfo(); return networkInfo.getType() == manager.TYPE_WIFI ? true : false; } /** * 判断MOBILE网络是否可用 * @param context * @return * @throws Exception */ public static boolean isMobileDataEnable(Context context){ ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); boolean isMobileDataEnable = false; isMobileDataEnable = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting(); return isMobileDataEnable; } /** * 判断wifi 是否可用 * @param context * @return * @throws Exception */ public static boolean isWifiDataEnable(Context context){ ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); boolean isWifiDataEnable = false; isWifiDataEnable = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting(); return isWifiDataEnable; } /** * 跳转到网络设置页面 * @param activity */ public static void GoSetting(Activity activity){ Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS); activity.startActivity(intent); } /** * 打开网络设置界面 */ public static void openSetting(Activity activity) { Intent intent = new Intent(“/”); ComponentName cn = new ComponentName(“com.android.settings”, “com.android.settings.WirelessSettings”); intent.setComponent(cn); intent.setAction(“android.intent.action.VIEW”); activity.startActivityForResult(intent, 0); } }

7 蓝牙

BluetoothAdapter blueadapter = BluetoothAdapter.getDefaultAdapter(); if (blueadapter == null) { bluetools.setVisibility(View.GONE); }

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片