75.android简单的获取当前可用运行内存,总运行内存。

//第一步 写个SystemMemory类来获取当前可用运行内存和总运行内存:

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




    /**
     *   * 获取android总运行内存大小
     *   * @param context
     *   *
     */
    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");
            }
            // 获得系统总内存,单位是KB
            int i = Integer.valueOf(arrayOfString[1]).intValue();
            //int值乘以1024转换为long类型
            initial_memory = new Long((long)i*1024);
            localBufferedReader.close();
        } catch (IOException e) {
        }
        return Formatter.formatFileSize(context, initial_memory);// Byte转换为KB或者MB,内存大小规格化
    }
}

//第二步 直接在Activity里调用就行了:

mText = (TextView) findViewById(R.id.mText);
//当前可用运行内存
String availMemory = SystemMemory.getAvailMemory(this);
//当前总运行内存
String totalMemory = SystemMemory.getTotalMemory(this);
mText.setText("当前可用运行内存"+availMemory+","+"当前总运行内存"+totalMemory);

//我的Activity布局就写了个TextView:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.hasee.zhulixiaodian.view.toolclass.MainActivity">

    <TextView
        android:id="@+id/mText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</android.support.constraint.ConstraintLayout>

//--------------------------------------------------------------完-----------------------------------------------------------------------

猜你喜欢

转载自blog.csdn.net/weixin_42061754/article/details/82969311
今日推荐