Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีดึงหน่วยความจำว่างของ Activity ใน Android

ภาพรวม

บทความนี้สาธิตวิธีดึงข้อมูลหน่วยความจำที่พร้อมใช้งาน (Available Memory) ของแอปผ่าน ActivityManager.MemoryInfo

ขั้นตอนที่ 1: สร้างโปรเจกต์

Android Studio → File → New Project → Empty Activity

ขั้นตอนที่ 2: Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="24sp"
        android:gravity="center"
        android:padding="16dp" />

</LinearLayout>

ขั้นตอนที่ 3: โค้ดหลัก (java/MainActivity.java)

package com.example.myapplication;

import android.app.ActivityManager;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.text);

        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
        activityManager.getMemoryInfo(memoryInfo);

        long availMem = memoryInfo.availMem;      // หน่วยความจำว่าง (bytes)
        long totalMem = memoryInfo.totalMem;      // หน่วยความจำทั้งหมด (API 16+)
        long threshold = memoryInfo.threshold;    // เกณฑ์ Low Memory (bytes)
        boolean lowMemory = memoryInfo.lowMemory; // สถานะ Low Memory

        String info = String.format(
            "หน่วยความจำว่าง: %s\n" +
            "หน่วยความจำทั้งหมด: %s\n" +
            "เกณฑ์ Low Memory: %s\n" +
            "สถานะ Low Memory: %s",
            formatBytes(availMem),
            formatBytes(totalMem),
            formatBytes(threshold),
            lowMemory ? "ใช่ (ต่ำ)" : "ปกติ"
        );

        textView.setText(info);
    }

    private String formatBytes(long bytes) {
        if (bytes < 1024) return bytes + " B";
        if (bytes < 1024 * 1024) return String.format("%.2f KB", bytes / 1024.0);
        if (bytes < 1024 * 1024 * 1024) return String.format("%.2f MB", bytes / (1024.0 * 1024));
        return String.format("%.2f GB", bytes / (1024.0 * 1024 * 1024));
    }
}

MemoryInfo Fields

FieldคำอธิบายAPI Level
availMemหน่วยความจำที่จัดสรรให้แอปได้ (bytes)16+
totalMemหน่วยความจำทั้งหมดของระบบ (bytes)16+
thresholdเกณฑ์ที่ถือว่า Low Memory (bytes)16+
lowMemorytrue ถ้าระบบอยู่ในสภาวะ Low Memory16+

ข้อมูลเพิ่มเติมจาก ActivityManager

// Memory class ของแอปนี้
int memoryClass = activityManager.getMemoryClass(); // MB
int largeMemoryClass = activityManager.getLargeMemoryClass(); // MB สำหรับ largeHeap

// Process memory info
Debug.MemoryInfo[] memInfo = activityManager.getProcessMemoryInfo(new int[]{android.os.Process.myPid()});
long pss = memInfo[0].getTotalPss() * 1024; // Proportional Set Size (bytes)

กรณีใช้งาน

  • ตัดสินใจโหลดรูปภาพขนาดใหญ่หรือไม่
  • ปรับคุณภาพวิดีโอ/รูปภาพตาม RAM
  • เตือนผู้ใช้เมื่อหน่วยความจำต่ำ
  • Debug memory leak

ทดสอบ

รันแอป จะแสดง Available Memory, Total Memory, Threshold ในหน่วย KB/MB/GB