手机一些信息的获取(电池相关、versionName、屏幕相关等)

收集整理了一些关于手机信息的获取方法。不够全面,以后会陆续补充,旨在方便开发。和另一个工具类相辅相成吧。可能会有重复的。酌情使用。
我把另一个工具类的链接放至此处:
点我进入

获取手机电池容量信息

//获取电池容量
    public static String getBatteryCapacity(Context context) {
        Object mPowerProfile;
        double batteryCapacity = 0;
        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);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return String.valueOf(batteryCapacity);
    }

获取手机电量百分比

public static int getBatteryCurrent(Context context) {
        int capacity = 0;
        try {
            BatteryManager manager = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
            capacity = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);//当前电量剩余百分比
        } catch (Exception e) {

        }
        return capacity;
    }

获取app versionName

public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }

获取系统磁盘大小

 public static String getTotalRom() {
        File dataDir = Environment.getDataDirectory();
        StatFs stat = new StatFs(dataDir.getPath());
        long blockSize = stat.getBlockSizeLong();
        long totalBlocks = stat.getBlockCountLong();
        long size = totalBlocks * blockSize;
        long GB = 1024 * 1024 * 1024;
        final long[] deviceRomMemoryMap = {2 * GB, 4 * GB, 8 * GB, 16 * GB, 32 * GB, 64 * GB, 128 * GB, 256 * GB, 512 * GB, 1024 * GB, 2048 * GB};
        String[] displayRomSize = {"2GB", "4GB", "8GB", "16GB", "32GB", "64GB", "128GB", "256GB", "512GB", "1024GB", "2048GB"};
        int i;
        for (i = 0; i < deviceRomMemoryMap.length; i++) {
            if (size <= deviceRomMemoryMap[i]) {
                break;
            }
            if (i == deviceRomMemoryMap.length) {
                i--;
            }
        }
        return displayRomSize[i];
    }

获取剩余可用系统磁盘大小

/**
     * 剩余可用磁盘大小
     */
    public static String getTotalMemory() {
        //获取ROM内存信息
        //调用该类来获取磁盘信息(而getDataDirectory就是内部存储)
        final StatFs statFs = new StatFs(Environment.getDataDirectory().getPath());
        long totalCounts = statFs.getBlockCountLong();//总共的block数
        long availableCounts = statFs.getAvailableBlocksLong(); //获取可用的block数
        long size = statFs.getBlockSizeLong(); //每格所占的大小,一般是4KB==
        long availROMSize = availableCounts * size;//可用内部存储大小
        long totalROMSize = totalCounts * size; //内部存储总大小
        return bytes2kb(availROMSize);
    }

    private static String bytes2kb(long bytes) {
        DecimalFormat format = new DecimalFormat("##.00");
        if (bytes / GB >= 1) {
            return format.format(bytes / GB) + "GB";
        } else if (bytes / MB >= 1) {
            return format.format(bytes / MB) + "MB";
        } else if (bytes / KB >= 1) {
            return format.format(bytes / KB) + "KB";
        } else {
            return bytes + "KB";
        }
    }

获取电池电量百分比

@RequiresApi(api = Build.VERSION_CODES.M)
    public static String getBatteryInfo(Activity host) {
        BatteryManager manager = (BatteryManager) host.getSystemService(BATTERY_SERVICE);
        int bt = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);///当前电量百分比
        return bt + "";
    }

获取RAM大小

public static String getRamSize(Activity host) {
        //获取运行内存的信息
        ActivityManager manager = (ActivityManager) host.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo();
        manager.getMemoryInfo(info);
        return (info.totalMem / 1024 / 1024 / 1024) + "G";
    }

获取占用RAM大小

public static String getTotalRam(Activity host) {
        //获取运行内存的信息
        ActivityManager manager = (ActivityManager) host.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo();
        manager.getMemoryInfo(info);
        StringBuilder sb = new StringBuilder();
        long l = (info.totalMem / 1024 / 1024 / 1024) - (info.availMem / 1024 / 1024 / 1024);
        return l + "";
      /*  LogUtil.d("可用RAM:" + info.availMem / 1024 / 1024 / 1024 + "GB");
        LogUtil.d("总RAM:" + info.totalMem / 1024 / 1024 / 1024 + "GB");*/
    }

获取RAM剩余百分比

public static String getRatioRam(Activity host) {
        //获取运行内存的信息
        ActivityManager manager = (ActivityManager) host.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo();
        manager.getMemoryInfo(info);
        long zy = info.totalMem - info.availMem;
        //float num = (float) (Math.round((zy / info.totalMem) / 1024 / 1024 / 1024));
        long num = ((zy / info.totalMem) / 1024 / 1024 / 1024);
        return num + "";
    }

除此之外。还有一些获取手机各种信息的。可能有重复。请选择合适的使用

还是要添加权限的

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.READ_PHONE_STATE"/>

然后创建广播

 private BroadcastReceiver batteryReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            getCell(intent);    //获取手机电池信息
            Network();          //获取网络信息
        }
    };
    
//此广播要在onCreate中注册,如下:
registerReceiver(context, batteryReceiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED)) 

上面调用的两个方法,如下:

 /** 获取手机电池信息 */
    @SuppressLint("SetTextI18n")
    private void getCell(Intent intent) {

        int mLevel = intent.getIntExtra("level", 0);  //电池电量
        int BatteryV = intent.getIntExtra("voltage", 0);  //电池电压
        int BatteryT = intent.getIntExtra("temperature", 0);  //电池温度

        TextView Cell01 = findViewById(R.id.Cell01);
        TextView Cell02 = findViewById(R.id.Cell02);
        TextView Cell03 = findViewById(R.id.Cell03);
        TextView Cell04 = findViewById(R.id.Cell04);
        TextView Cell05 = findViewById(R.id.Cell05);
        Cell01.setText("电池电量:" + mLevel + "%");
        Cell02.setText("电池电压:" + (BatteryV * 0.001) + "V");
        Cell03.setText("电池温度:" + (BatteryT * 0.001) + "℃");

        switch (intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN)) {
            case BatteryManager.BATTERY_STATUS_CHARGING:
                Cell04.setText("电池状态:充电状态");break;
            case BatteryManager.BATTERY_STATUS_DISCHARGING:
                Cell04.setText("电池状态:放电状态");break;
            case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
                Cell04.setText("电池状态:未充电");break;
            case BatteryManager.BATTERY_STATUS_FULL:
                Cell04.setText("电池状态:充满电");break;
            case BatteryManager.BATTERY_STATUS_UNKNOWN:
                Cell04.setText("电池状态:未知道状态");break;
        }
        switch (intent.getIntExtra("health", BatteryManager.BATTERY_HEALTH_UNKNOWN)) {
            case BatteryManager.BATTERY_HEALTH_UNKNOWN:
                Cell05.setText("电池报警:未知错误");break;
            case BatteryManager.BATTERY_HEALTH_GOOD:
                Cell05.setText("电池报警:电池状态良好");break;
            case BatteryManager.BATTERY_HEALTH_DEAD:
                Cell05.setText("电池报警:电池没有电");break;
            case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
                Cell05.setText("电池报警:电池电压过高");break;
            case BatteryManager.BATTERY_HEALTH_OVERHEAT:
                Cell05.setText("电池报警:电池过热");break;
        }
    }


/** 获取网络信息 */
    @SuppressLint("SetTextI18n")
    private void Network() {
        TextView Network01 = findViewById(R.id.Network01);
        TextView Network02 = findViewById(R.id.Network02);
        TextView Network03 = findViewById(R.id.Network03);
        TextView Network04 = findViewById(R.id.Network04);
        TextView Network05 = findViewById(R.id.Network05);

        if(isNetworkConnected(MainActivity.this)){
            Network01.setText("网路连接:网络连接成功");
        }else{
            Network01.setText("网路连接:网络连接失败");
        }

        if(isWifiConnected(MainActivity.this)){
            Network02.setText("Wifi 网络:支持");
        }else{
            Network02.setText("Wifi 网络:不支持");
        }

        if(isMobileConnected(MainActivity.this)){
            Network03.setText("数据网络:可用");
        }else{
            Network03.setText("数据网络:不可用");
        }

        switch (getConnectedType(MainActivity.this)){
            case -1: Network04.setText("网络类型:无网络");
                break;
            case 0: Network04.setText("网络类型:正在使用数据流量上网");
                break;
            case 1: Network04.setText("网络类型:正在使用 Wifi上网");
                break;
            default: Network04.setText("网络类型:未知网络");
                break;
        }

        //没有网络0:WIFI网络1:3G网络2:2G网络3
        switch (getAPNType(MainActivity.this)){
            case 0: Network05.setText("网络状态:无网络");
                break;
            case 1: Network05.setText("网络状态:WIFI网络");
                break;
            case 2: Network05.setText("网络状态:3G网络");
                break;
            case 3: Network05.setText("网络状态:4G网络");
                break;
            default: Network05.setText("网络状态:其他网络");
                break;
        }
    }

此外还有一些其他的:

	/**  获取当前屏幕的像素密度 */      //像素密度density,表示一个dp包含多少个Px单位,和标准dpi的比例(160px/inc)
    public static float getScreenDensity(Context context) {
        //获取系统服务
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);  //获取显示参数保存到dm中
        return dm.density * 160;   //返回屏幕的宽度
    }


    /** 计算屏幕尺寸 */
    public static String getMeasure(int height, int width, int dpi) {
        float x = (float) sqrt(((height * height) + (width * width)) / (dpi * dpi));
        DecimalFormat decimalFormat = new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
        String str = decimalFormat.format(x);  //format 返回的是字符串
        return str;   //返回屏幕的宽度
    }


	/** 获取当前屏幕的高度 */
    public static int getScreenHeight(Context context) {
        //获取系统服务
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);  //获取显示参数保存到dm中
        return dm.heightPixels;   //返回屏幕的宽度
    }
    

    /** 获取当前屏幕的宽度 */
    public static int getScreenWidth(Context context) {
        //获取系统服务
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);  //获取显示参数保存到dm中
        return dm.widthPixels;   //返回屏幕的宽度
    }

** 获取当前可用运行内存大小 */
    public static String getAvailMemory(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        return Formatter.formatFileSize(context, mi.availMem);// 将获取的内存大小规格化
    }


    /** 获取android总运行内存大小 */
    public static String getTotalMemory(Context context) {
        String str1 = "/proc/meminfo";// 系统内存信息文件
        String str2;
        String[] arrayOfString;
        long initial_memory = 0;
        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);
            str2 = localBufferedReader.readLine();// 读取meminfo第一行,系统总内存大小
            arrayOfString = str2.split("\\s+");
            for (String num : arrayOfString) {
                Log.i(str2, num + "\t");
            }
            int i = Integer.valueOf(arrayOfString[1]);// 获得系统总内存,单位是KB
            initial_memory = (long) i * 1024;//int值乘以1024转换为long类型
            localBufferedReader.close();
        } catch (IOException ignored) {
        }
        return Formatter.formatFileSize(context, initial_memory);// Byte转换为KB或者MB,内存大小规格化
    }

    /** 获取手机内部存储空间,以M,G为单位的容量 */
    public static String getInternalMemorySize(Context context) {
        File file = Environment.getDataDirectory();
        StatFs statFs = new StatFs(file.getPath());
        long blockSizeLong = statFs.getBlockSizeLong();
        long blockCountLong = statFs.getBlockCountLong();
        long size = blockCountLong * blockSizeLong;
        return Formatter.formatFileSize(context, size);
    }

    /** 获取手机内部可用存储空间,以M,G为单位的容量 */
    public static String getAvailableInternalMemorySize(Context context) {
        File file = Environment.getDataDirectory();
        StatFs statFs = new StatFs(file.getPath());
        long availableBlocksLong = statFs.getAvailableBlocksLong();
        long blockSizeLong = statFs.getBlockSizeLong();
        return Formatter.formatFileSize(context, availableBlocksLong * blockSizeLong);
    }

    /** 是否有网络连接 */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /** WiFi是否可用 */
    public static boolean isWifiConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (mWiFiNetworkInfo != null) {
                return mWiFiNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /** 数据流量是否可用 */
    public static boolean isMobileConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mMobileNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (mMobileNetworkInfo != null) {
                return mMobileNetworkInfo.isAvailable();
            }
        }
        return false;
    }


/** 获取当前的网络状态 */
    public static int getAPNType(Context context) {
        int netType = 0;
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = 1;   // wifi
        } else if (nType == ConnectivityManager.TYPE_MOBILE) {
            int nSubType = networkInfo.getSubtype();
            TelephonyManager mTelephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (nSubType == TelephonyManager.NETWORK_TYPE_UMTS && !mTelephony.isNetworkRoaming()) {
                netType = 2;// 3G
            } else {
                netType = 3;// 4G
            }
        }
        return netType;
    }

好人一生平安。
END

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值