• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2023 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 package org.chromium.base.memory;
6 
7 import android.app.ActivityManager;
8 import android.content.Context;
9 import android.os.Debug;
10 import android.os.Process;
11 
12 import androidx.annotation.Nullable;
13 
14 import org.jni_zero.CalledByNative;
15 
16 import org.chromium.base.ContextUtils;
17 
18 /** Allows calling ActivityManager#getProcessMemoryInfo() from native. */
19 public class MemoryInfoBridge {
20     /**
21      * Returns the result of ActivityManager#getProcessMemoryInfo() on itself.
22      *
23      * Calls to this method are heavily throttled in ActivityManager, with stale results silently
24      * returned when called too often. Should not be called outside of the native caller, as the
25      * throttling handling code there would become incorrect otherwise.
26      */
27     @CalledByNative
getActivityManagerMemoryInfoForSelf()28     public static @Nullable Debug.MemoryInfo getActivityManagerMemoryInfoForSelf() {
29         ActivityManager activityManager =
30                 (ActivityManager)
31                         ContextUtils.getApplicationContext()
32                                 .getSystemService(Context.ACTIVITY_SERVICE);
33         int pid = Process.myPid();
34         try {
35             Debug.MemoryInfo[] infos = activityManager.getProcessMemoryInfo(new int[] {pid});
36             return infos == null ? null : infos[0];
37         } catch (SecurityException e) {
38             // Isolated callers are not allowed. Since this is used for logging only, don't crash in
39             // this case. Also, prevents issues if the framework further restricts this API (which
40             // has happened, with a restriction on PIDs starting in Q).
41             return null;
42         }
43     }
44 }
45