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

Kiểm tra lượng RAM sử dụng bởi ứng dụng Android

Kiểm tra lượng RAM sử dụng bởi ứng dụng Android

Hướng dẫn này minh họa cách lấy thông tin bộ nhớ (RAM) của thiết bị và ứng dụng bằng ActivityManager.MemoryInfo và Runtime.

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.

Bước 2: Thiết kế giao diện (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/text"
        android:textStyle="bold"
        android:textSize="24sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />
</RelativeLayout>

Bước 3: Code MainActivity.java

import android.app.ActivityManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        final TextView textView = findViewById(R.id.text);
        textView.setText(getMemoryInfo());
    }
    
    private String getMemoryInfo() {
        // Thông tin bộ nhớ hệ thống
        ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
        ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        activityManager.getMemoryInfo(memoryInfo);
        
        // Thông tin bộ nhớ JVM/Process
        Runtime runtime = Runtime.getRuntime();
        
        StringBuilder builder = new StringBuilder();
        builder.append("=== System Memory (ActivityManager) ===\n")
               .append("Available Memory: ").append(formatBytes(memoryInfo.availMem)).append("\n")
               .append("Total Memory: ").append(formatBytes(memoryInfo.totalMem)).append("\n")
               .append("Threshold: ").append(formatBytes(memoryInfo.threshold)).append("\n")
               .append("Low Memory: ").append(memoryInfo.lowMemory).append("\n\n")
               
               .append("=== Process Memory (Runtime) ===\n")
               .append("Max Memory: ").append(formatBytes(runtime.maxMemory())).append("\n")
               .append("Total Memory: ").append(formatBytes(runtime.totalMemory())).append("\n")
               .append("Free Memory: ").append(formatBytes(runtime.freeMemory())).append("\n")
               .append("Used Memory: ").append(formatBytes(runtime.totalMemory() - runtime.freeMemory())).append("\n");
        
        return builder.toString();
    }
    
    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));
    }
}

Bước 4: Cấu hình AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị, chạy app. TextView sẽ hiển thị chi tiết bộ nhớ: Available, Total, Threshold (hệ thống) và Max, Total, Free, Used (process/app).

Giải thích các chỉ số:
  • ActivityManager.MemoryInfo: Thông tin bộ nhớ TOÀN HỆ THỐNG
    • availMem: RAM khả dụng cho ứng dụng mới
    • totalMem: Tổng RAM vật lý thiết bị
    • threshold: Ngưỡng low memory (khi availMem < threshold → lowMemory=true)
    • lowMemory: true nếu hệ thống thiếu RAM
  • Runtime: Thông tin bộ nhớ CỦA TIẾN TRÌNH (PROCESS) hiện tại
    • maxMemory(): Giới hạn heap tối đa app có thể dùng (dalvik.vm.heapsize)
    • totalMemory(): Heap hiện tại đã cấp phát
    • freeMemory(): Heap chưa sử dụng trong totalMemory
    • totalMemory() - freeMemory(): Heap đang sử dụng thực tế

Lấy Memory Info chi tiết hơn (API 16+)

// MemoryInfo của process cụ thể
ActivityManager.MemoryInfo[] processMemoryInfo = activityManager.getProcessMemoryInfo(new int[]{android.os.Process.myPid()});
if (processMemoryInfo.length > 0) {
    Debug.MemoryInfo info = processMemoryInfo[0];
    // info.dalvikPss, info.nativePss, info.otherPss, info.getTotalPss()
}

// Lấy danh sách process và memory
List<ActivityManager.RunningAppProcessInfo> processes = activityManager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo process : processes) {
    int pid = process.pid;
    String name = process.processName;
    // getProcessMemoryInfo([pid]) để xem chi tiết
}

Đọc /proc/meminfo (Root/ADB)

// Chỉ hoạt động trên rooted device hoặc qua ADB
// cat /proc/meminfo
// MemTotal, MemFree, MemAvailable, Buffers, Cached, SwapTotal, SwapFree...