1 | // Copyright 2013 The Chromium Authors. All rights reserved. |
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; |
6 | |
7 | import android.content.ComponentCallbacks2; |
8 | import android.content.Context; |
9 | import android.content.res.Configuration; |
10 | |
11 | |
12 | /** |
13 | * This is an internal implementation of the C++ counterpart. |
14 | * It registers a ComponentCallbacks2 with the system, and dispatches into |
15 | * native. |
16 | */ |
17 | public class MemoryPressureListener { |
18 | @CalledByNative |
19 | private static void registerSystemCallback(Context context) { |
20 | context.registerComponentCallbacks( |
21 | new ComponentCallbacks2() { |
22 | @Override |
23 | public void onTrimMemory(int level) { |
24 | maybeNotifyMemoryPresure(level); |
25 | } |
26 | |
27 | @Override |
28 | public void onLowMemory() { |
29 | nativeOnMemoryPressure(MemoryPressureLevelList.MEMORY_PRESSURE_CRITICAL); |
30 | } |
31 | |
32 | @Override |
33 | public void onConfigurationChanged(Configuration configuration) { |
34 | } |
35 | }); |
36 | } |
37 | |
38 | /** |
39 | * Used by applications to simulate a memory pressure signal. |
40 | */ |
41 | public static void simulateMemoryPressureSignal(int level) { |
42 | maybeNotifyMemoryPresure(level); |
43 | } |
44 | |
45 | private static void maybeNotifyMemoryPresure(int level) { |
46 | if (level == ComponentCallbacks2.TRIM_MEMORY_COMPLETE) { |
47 | nativeOnMemoryPressure(MemoryPressureLevelList.MEMORY_PRESSURE_CRITICAL); |
48 | } else if (level >= ComponentCallbacks2.TRIM_MEMORY_BACKGROUND || |
49 | level == ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL) { |
50 | nativeOnMemoryPressure(MemoryPressureLevelList.MEMORY_PRESSURE_MODERATE); |
51 | } |
52 | } |
53 | |
54 | private static native void nativeOnMemoryPressure(int memoryPressureType); |
55 | } |