Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách lấy bộ nhớ khả dụng (Available Memory) của Activity trên Android

Giới thiệu

Bài viết hướng dẫn lấy thông tin bộ nhớ khả dụng (available memory) của thiết bị qua ActivityManager.MemoryInfo. Lưu ý: Đây là bộ nhớ hệ thống, không phải bộ nhớ của process ứng dụng.

Các bước thực hiện

Bước 1: Tạo project mới

Android Studio → File → New Project → Empty Activity.

Bước 2: Giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="16dp">

    <TextView
        android:id="@+id/tvMemoryInfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Memory Info"
        android:textSize="16sp"
        android:lineSpacingExtra="4dp" />

</LinearLayout>

Bước 3: Code (MainActivity.kt)

package com.example.memoryinfo

import android.app.ActivityManager
import android.content.Context
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        showMemoryInfo()
    }

    private fun showMemoryInfo() {
        val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val memoryInfo = ActivityManager.MemoryInfo()
        activityManager.getMemoryInfo(memoryInfo)

        val sb = StringBuilder()
        sb.appendLine("=== System Memory Info ===")
        sb.appendLine("Available Memory: ${formatBytes(memoryInfo.availMem)}")
        sb.appendLine("Total Memory: ${formatBytes(memoryInfo.totalMem)}")
        sb.appendLine("Threshold (Low Memory): ${formatBytes(memoryInfo.threshold)}")
        sb.appendLine("Is Low Memory: ${memoryInfo.lowMemory}")

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            sb.appendLine("--------------------------------")
            sb.appendLine("App Memory Limit: ${formatBytes(activityManager.memoryClass.toLong() * 1024 * 1024)}")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                sb.appendLine("App Large Memory Limit: ${formatBytes(activityManager.largeMemoryClass.toLong() * 1024 * 1024)}")
            }
        }

        tvMemoryInfo.text = sb.toString()
    }

    private fun formatBytes(bytes: Long): String {
        return when {
            bytes >= 1024 * 1024 * 1024 -> String.format("%.2f GB", bytes / (1024.0 * 1024 * 1024))
            bytes >= 1024 * 1024 -> String.format("%.2f MB", bytes / (1024.0 * 1024))
            bytes >= 1024 -> String.format("%.2f KB", bytes / 1024.0)
            else -> "$bytes B"
        }
    }

    companion object {
        @Suppress("UNUSED_PARAMETER")
        @JvmStatic
        fun main(args: Array<String>) {}
    }
}

Giải thích các trường MemoryInfo

Trường Ý nghĩa Đơn vị
availMem Bộ nhớ khả dụng cho hệ thống/alloc mới Bytes
totalMem Tổng bộ nhớ RAM vật lý (API 16+) Bytes
threshold Ngưỡng low memory (khi availMem < threshold → lowMemory=true) Bytes
lowMemory True nếu hệ thống đang thiếu память Boolean

Lấy bộ nhớ của Process ứng dụng (App Memory)

// Memory info của process hiện tại
val debugMemoryInfo = Debug.MemoryInfo()
Debug.getMemoryInfo(debugMemoryInfo)
val pss = debugMemoryInfo.getTotalPss() // KB - Proportional Set Size
val privateDirty = debugMemoryInfo.getTotalPrivateDirty() // KB

// Hoặc dùng ActivityManager.getProcessMemoryInfo()
val pids = intArrayOf(android.os.Process.myPid())
val processMemoryInfo = activityManager.getProcessMemoryInfo(pids)
val pssTotal = processMemoryInfo[0].totalPss // KB

Lưu ý

  • availMem là bộ nhớ hệ thống, không phải heap của app.
  • memoryClass: Giới hạn heap tối đa cho app (MB), thường 128MB - 512MB tùy thiết bị.
  • largeMemoryClass: Giới hạn cho app khai báo android:largeHeap="true" trong Manifest.
  • Không nên dựa vào availMem để quyết định allocate memory lớn - hệ thống quản lý động.
  • Dùng Debug.MemoryInfo hoặc Profiling tools (Android Studio Profiler) để phân tích memory leak chính xác.