From cc5fa8370b1e241f189a490e06f048beeceadb67 Mon Sep 17 00:00:00 2001 From: duqingquan Date: Wed, 2 Nov 2022 16:05:28 +0800 Subject: [PATCH] uts-memory plugin basic done. --- uni_modules/uni-memorywarning/package.json | 3 +- .../utssdk/app-android/index.uts | 49 +++++++++++++------ 2 files changed, 37 insertions(+), 15 deletions(-) diff --git a/uni_modules/uni-memorywarning/package.json b/uni_modules/uni-memorywarning/package.json index 071d268..a31a9a0 100644 --- a/uni_modules/uni-memorywarning/package.json +++ b/uni_modules/uni-memorywarning/package.json @@ -33,7 +33,8 @@ "uni_modules": { "uni-ext-api":{ "uni": { - "onMemoryWarning": "onMemoryWarning" + "onMemoryWarning": "onMemoryWarning", + "offMemoryWarning":"offMemoryWarning" }, "mp-weixin":false, "mp-alipay":false, diff --git a/uni_modules/uni-memorywarning/utssdk/app-android/index.uts b/uni_modules/uni-memorywarning/utssdk/app-android/index.uts index 7a506cf..d0aa13e 100644 --- a/uni_modules/uni-memorywarning/utssdk/app-android/index.uts +++ b/uni_modules/uni-memorywarning/utssdk/app-android/index.uts @@ -1,20 +1,41 @@ -import { onAppTrimMemory } from "io.dcloud.uts.android"; +import { onAppTrimMemory, offAppTrimMemory ,onAppActivityDestroy} from "io.dcloud.uts.android" -export function onMemoryWarning(callback: (res:Number) => void) { - // console.log("here"); - onAppTrimMemory((level:Number) => { - console.log(level); - callback(level); - }); - // return ; +let listeners: UTSCallback[] = [] + +const onAppTrimMemoryListener = (res: number) => { + listeners.forEach(listener => { + console.log("listener " + listener); + listener(res) + }) } +export function onMemoryWarning(callback: (res: number) => void) { + + if (listeners.length === 0) { + // 仅首次执行底层的实际监听 + onAppTrimMemory(onAppTrimMemoryListener) + onAppActivityDestroy(()=>{ + // listeners 默认是静态常量周期,activity 销毁时,需要手动清空 + listeners = [] + }) + } + listeners.push(callback) +} -export function offMemoryWarning(success: (res: any) => void) { - // TODO 没有实现卸载监听 - let ret = { - code:0 +export function offMemoryWarning(callback: ((res: number) => void) | null) { + + if(callback == null){ + // 清除全部回调 + listeners = [] + return } - success(ret); + // 清除指定回调 + const index = listeners.indexOf(callback) + if (index > -1) { + listeners.splice(index, 1) + } + if (listeners.length === 0) { + // 当用户不再监听时,移除底层实际监听 + offAppTrimMemory(onAppTrimMemoryListener) + } } - -- GitLab