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

Cách xóa giới hạn heap watch (clearWatchHeapLimit) trên Android

Giới thiệu

Bài viết hướng dẫn sử dụng ActivityManager.clearWatchHeapLimit() để xóa giới hạn theo dõi heap (heap watch limit) đã được thiết lập trước đó bởi setWatchHeapLimit(). Đây là API dành cho debug/profiling memory.

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/tvStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Heap watch limit cleared"
        android:textSize="18sp" />

</LinearLayout>

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

package com.example.clearheapwatch

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)

        val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager

        // Xóa heap watch limit
        activityManager.clearWatchHeapLimit()

        tvStatus.text = "Heap watch limit đã được xóa (clearWatchHeapLimit)"
    }
}

Bối cảnh: Heap Watch Limit là gì?

  • setWatchHeapLimit(limitInBytes): Thiết lập ngưỡng heap size. Khi heap của process vượt ngưỡng này, hệ thống sẽ ghi log warning hoặc trigger GC.
  • clearWatchHeapLimit(): Xóa ngưỡng đó, tắt cảnh báo.
  • Dùng chủ yếu cho **debugging memory leak**, profiling trong development.
  • Không ảnh hưởng đến runtime behavior của app bình thường.

Ví dụ đầy đủ: Set và Clear

val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager

// Set watch limit: 50 MB
val watchLimit = 50 * 1024 * 1024L // 50MB in bytes
activityManager.setWatchHeapLimit(watchLimit)
Log.d("HeapWatch", "Set watch limit to 50MB")

// ... run app, test memory usage ...

// Clear watch limit khi xong
activityManager.clearWatchHeapLimit()
Log.d("HeapWatch", "Cleared watch limit")

Lưu ý quan trọng

  • Yêu cầu quyền: Cần quyền android.permission.SET_ACTIVITY_WATCHER (signature|privileged) - **chỉ system app hoặc root mới dùng được**.
  • App thông thường **không thể gọi** các API này thành công (sẽ throw SecurityException hoặc no-op).
  • Dùng cho: Framework development, custom ROM, automated testing framework.
  • Cho app development thông thường: Dùng Android Studio Profiler, Debug.getNativeHeapAllocatedSize(), ActivityManager.getMemoryInfo(), LeakCanary.

Cách debug memory cho app thường

// Lấy heap info của process hiện tại
val debugInfo = Debug.MemoryInfo()
Debug.getMemoryInfo(debugInfo)
val nativeHeap = debugInfo.nativeHeapAllocatedSize // bytes
val dalvikHeap = debugInfo.dalvikHeapAllocatedSize // bytes (deprecated)

// Hoặc dùng ActivityManager
val am = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val myMemoryInfo = arrayOfNulls(1)
am.getProcessMemoryInfo(intArrayOf(Process.myPid()), myMemoryInfo)
val pss = myMemoryInfo[0]?.totalPss ?: 0 // KB