为了安全考虑,例如Toast恶意遮挡其他页面,Toast只能显示在当前的UI实例中,应用退出后,不会单独显示在桌面上。若是想在应用退出到后台时继续提醒用户,可以使用横幅通知功能。
import { notificationManager } from '@kit.NotificationKit';
// 通知方法 publishNotification() { let notificationRequest: // 描述通知的请求 notificationManager.NotificationRequest = { // 通知ID id: 1, // 通知内容 content: { notificationContentType: // 普通文本类型通知 notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 基本类型通知内容 normal: { title: '应用名称', text: '应用在后台运行' }, }, notificationSlotType: notificationManager.SlotType.SOCIAL_COMMUNICATION, }; // 发布通知 notificationManager.publish(notificationRequest).then(() => { console.info('publish success'); }).catch((err: Error) => { console.error(`publish failed,message is ${err}`); }); } onBackground(): void { this.publishNotification(); // Ability has back to background hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground'); }
@Entry @Component struct Index { @State message: string = 'Hello World'; build() { RelativeContainer() { Text(this.message) .id('HelloWorld') .fontSize($r('app.float.page_text_font_size')) .fontWeight(FontWeight.Bold) .alignRules({ center: { anchor: '__container__', align: VerticalAlign.Center }, middle: { anchor: '__container__', align: HorizontalAlign.Center } }) .onClick(() => { this.message = 'Welcome'; }); } .height('100%') .width('100%'); } }
Q:横幅通知可以提醒用户APP进入后台,是否有其他方案来实现?
A:可以使用SoundPool播放自定义的提示音来提醒用户。这可以让用户听到明显的音频提示,知道应用已经转到后台。具体开发步骤及注意事项可以参考:使用SoundPool播放短音频。