如下图应用有重写onBackPress方法,同时在两次侧滑退出应用时有调用KillApplicationSelf方法关闭应用进程,第二次侧滑操作与关闭应用进程时间间隔1.2s,推测应用在侧滑响应处理时延迟退出应用进程。
07-03 15:04:24.825 56626-56626 C03925/com.exa...ion/AceRouter com.examp...lication I [(100000:100000:scope)] router user onBackPress return true 07-03 15:04:25.503 56626-56626 C03925/com.exa...ion/AceRouter com.examp...lication I [(100000:100000:scope)] router user onBackPress return true 07-03 15:04:26.710 1458-2344 C01311/foundation/AppMS foundation W [ams_mgr_stub.cpp:431]KillApplicationSelf,callingPid=56626
onBackPress(): boolean | void {
if (this.first) {
this.first = false;
// 延迟一段时间将this.first设置成true
} else {
setTimeout(() => {
this.getUIContext().getHostContext()?.getApplicationContext().killAllProcesses().catch(() => {
// TODO:Implement error handling.
});
}, 1200);
}
return true;
} import { PromptAction } from '@ohos.arkui.UIContext';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@ohos.base';
@Entry
@Component
struct ExitPromptDemoPage {
message: string = 'Hello World';
promptAction: PromptAction = this.getUIContext().getPromptAction();
context = this.getUIContext().getHostContext() as common.UIAbilityContext;
private first: boolean = true;
firstBackPress(): void {
this.first = false;
this.showToast('再次侧滑退出', 1500);
setTimeout(() => {
this.first = true;
}, 1500);
}
showToast(message: string, duration: number) {
try {
this.promptAction.showToast({
message: message,
duration: duration
});
} catch (error) {
console.error('error: ', error);
}
}
terminate() {
this.context?.terminateSelf((err: BusinessError) => {
if (err.code) {
console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`);
}
console.info('terminateSelf succeed');
});
}
onBackPress(): boolean | void {
if (this.first) {
// 第一次侧滑处理
this.firstBackPress();
} else {
// 第二次侧滑处理
this.showToast('应用退出中', 3000);
setTimeout(() => {
this.terminate();
}, 3000);
}
return true;
}
build() {
RelativeContainer() {
Text(this.message)
.id('ExitPromptDemoPageHelloWorld')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
})
}
.height('100%')
.width('100%')
}
}