my.onMemoryWarning

Use this API to listen to the insufficient memory alarm event.

For Android, two alarm levels exist:

  • TRIM_MEMORY_RUNNING_LOW
  • TRIM_MEMORY_RUNNING_CRITICAL

No alarm level is available for iOS.

Sample Code

copy
// API-DEMO page/API/memory-warning/memory-warning.json
{
   "defaultTitle": "OnMemoryWarning"
}
copy
<!-- API-DEMO page/API/memory-warning/memory-warning.axml-->
<view class="page">

  <button type="primary" onTap="onMemoryWarning">
    Listen to Insufficient Memory Alarm Event
  </button>

</view>
copy
// API-DEMO page/API/memory-warning/memory-warning.js
Page({
  onLoad() {
    this.callback = (res) => {
        var levelString = 'iOS device, No alarm level exists.';
        switch (res.level) {
          case 10:
            levelString = 'Android device, level = TRIM_MEMORY_RUNNING_LOW';
            break;
          case 15:
            levelString = 'Android device, level = TRIM_MEMORY_RUNNING_CRITICAL';
            break;
        }
        my.alert({
          title: 'Received insufficient memory alarm',
          content: levelString
        });
    };
    this.isApiAvailable = my.canIUse('onMemoryWarning');
  },
  onMemoryWarning() {
    if (this.isApiAvailable) {
      my.onMemoryWarning(this.callback);
    } else {
      my.alert({
        title: 'Client version is too low',
        content: 'my.onMemoryWarning() and my.offMemoryWarning() need 10.1.35 or higher versions'
      });
    }
  },
  onUnload() {
    if (this.isApiAvailable) {
      my.offMemoryWarning(this.callback); 
    }
  }
});

Parameters

The property is a callback function which uses object properties with the following property:

PropertyTypeDescription
levelNumberMemory alarm level, only available in Android.

Android alarm levels that correspond to the system macro definitions:

copy
int TRIM_MEMORY_RUNNING_LOW = 10
int TRIM_MEMORY_RUNNING_CRITICAL = 15