index.uts 1.4 KB
Newer Older
1
import { UTSAndroid } from "io.dcloud.uts"
2
import { OnMemoryWarning, OffMemoryWarning, MemoryWarningCallback, MemoryWarningCallbackResult } from "../interface.uts"
杜庆泉's avatar
杜庆泉 已提交
3

4
let listeners: MemoryWarningCallback[] = []
5 6

const onAppTrimMemoryListener = (ret: number) => {
7
    listeners.forEach(listener => {
8 9 10 11
      let res: MemoryWarningCallbackResult = {
        level:ret
      }
      listener(res)
12
    })
13 14
}

15 16

@Suppress("DEPRECATION")
17
export const onMemoryWarning : OnMemoryWarning =  function (callback: MemoryWarningCallback) {
18
    if (listeners.length == 0) {
杜庆泉's avatar
杜庆泉 已提交
19
		// 仅首次执行底层的实际监听
20 21
        UTSAndroid.onAppTrimMemory(onAppTrimMemoryListener)
		UTSAndroid.onAppActivityDestroy(()=>{
杜庆泉's avatar
杜庆泉 已提交
22 23 24
			// listeners 默认是静态常量周期,activity 销毁时,需要手动清空
			listeners = []
		})
25 26
    }
    listeners.push(callback)
杜庆泉's avatar
杜庆泉 已提交
27
}
28

29

30
@Suppress("DEPRECATION")
31
export const offMemoryWarning : OffMemoryWarning = function (callback: MemoryWarningCallback | null) {
32 33
	
	if(callback == null){
杜庆泉's avatar
杜庆泉 已提交
34 35
		// 清除全部回调
		listeners = []
36
		UTSAndroid.offAppTrimMemory(null);
杜庆泉's avatar
杜庆泉 已提交
37
		return
38
	}
39
	
杜庆泉's avatar
杜庆泉 已提交
40
	// 清除指定回调
41 42 43 44 45 46 47 48
    const index = listeners.indexOf(callback)
    if (index > -1) {
        listeners.splice(index, 1)
    }
    if (listeners.length == 0) {
        // 当用户不再监听时,移除底层实际监听
        UTSAndroid.offAppTrimMemory(onAppTrimMemoryListener)
    }
49
}
50