Skip to main content
Use this API to listen for system memory warning events. When the system is running low on memory, you can release unnecessary resources to prevent your Mini Program from being terminated.

Parameters

PropertyTypeRequiredDescription
callbackFunctionYesCallback function when memory warning occurs

Callback Parameters

PropertyTypeDescription
levelNumberMemory warning level (higher means more critical)

Memory Warning Levels

LevelDescription
10Low memory warning (iOS only)
15Critical memory warning (iOS only)
5Low memory warning (Android)

Code Example

Basic Usage

my.onMemoryWarning((res) => {
  console.log('Memory warning level:', res.level);
});

Release Resources on Warning

App({
  globalData: {
    cache: {},
    images: []
  },

  onLaunch() {
    my.onMemoryWarning((res) => {
      console.log('Memory warning:', res.level);
      this.releaseMemory(res.level);
    });
  },

  releaseMemory(level) {
    if (level >= 10) {
      // Clear cached data
      this.globalData.cache = {};

      // Clear large image arrays
      this.globalData.images = [];

      console.log('Memory released due to warning');
    }
  }
});

Page-Level Memory Management

Page({
  data: {
    largeDataSet: [],
    imageUrls: []
  },

  onLoad() {
    my.onMemoryWarning(this.handleMemoryWarning);
    this.loadData();
  },

  handleMemoryWarning(res) {
    if (res.level >= 10) {
      // Keep only essential data
      const essentialData = this.data.largeDataSet.slice(0, 10);
      this.setData({
        largeDataSet: essentialData,
        imageUrls: []
      });

      my.showToast({
        content: 'Cleared cache to free memory'
      });
    }
  },

  onUnload() {
    my.offMemoryWarning(this.handleMemoryWarning);
  }
});
When you receive a memory warning, release unused resources immediately. Failure to do so may result in your Mini Program being terminated by the system.

my.offMemoryWarning

Stop listening for warnings

my.getSystemInfo

Get system information