DEV Community

HarmonyOS
HarmonyOS

Posted on

How to implement a pop-up window prompt function when the application window is uninteractive for a specified time

Read the original article:How to implement a pop-up window prompt function when the application window is uninteractive for a specified time

Context

If the app is not used for a certain period of time, a pop-up window will pop up. How can I achieve this?

Description

on('noInteractionDetected') : Enables monitoring of no interaction events for this window within the specified timeout period. Interaction events support physical keyboard input events and screen touch click events, but do not support soft keyboard input events.
AlertDialog : Displays a warning pop-up component, which can set text content and response callback.

Solution / Approach

Implementation idea: Design a warning pop-up window by referring to the AlertDialog implementation solution, and then add a monitoring of the timeout without interaction in aboutToAppear to achieve the effect of opening the warning pop-up window after the timeout monitoring is triggered. The specific implementation steps are as follows:

1.Get the corresponding WindowStage instance in the EntryAbility.ets file and store it in AppStorage. The sample code is as follows:

   onWindowStageCreate(windowStage: window.WindowStage): void {
     AppStorage.setOrCreate('windowStage', windowStage)
   }
Enter fullscreen mode Exit fullscreen mode

2.To implement a warning pop-up window, the sample code is as follows:

   dialogControllerConfirm: CustomDialogController = new CustomDialogController({
       builder: AlertDialog({
         primaryTitle: 'Warning',
         secondaryTitle: 'Timeout Alert',
         content: 'Screen has been inactive for over 6 seconds.',
         primaryButton: {
           value: 'Cancel',
           action: () => {
           },
         },
         secondaryButton: {
           value: 'Confirm',
           role: ButtonRole.ERROR,
           action: () => {
             console.info('Callback when the second button is clicked')
           }
         },
       }),
     })
Enter fullscreen mode Exit fullscreen mode

3.In the aboutToAppear phase, use on('noInteractionDetected') to enable monitoring of no interaction events within the specified timeout period for this window. The sample code is as follows:

   aboutToAppear(): void {
     let windowClass: window.Window | undefined = undefined;
     if (this.windowStage){
       this.windowStage.getMainWindow((err: BusinessError, data) => {
         const errCode: number = err.code;
         if (errCode) {
           console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
           return;
         }
         windowClass = data;
         try {
           windowClass.on('noInteractionDetected', 6, () => {
             console.info('no interaction in 6s');
             this.dialogControllerConfirm.open()
           });
         } catch (exception) {
           console.error(`Failed to register callback. Cause code: ${exception.code}, message: ${exception.message}`);
         }
       })
     }
   }
Enter fullscreen mode Exit fullscreen mode

4.Complete code:

   import { window } from '@kit.ArkUI';
   import { BusinessError } from '@kit.BasicServicesKit';
   import { AlertDialog } from '@kit.ArkUI';

   @Entry
   @Component
   struct Index {
     @State message: string = 'Hello World';
     @StorageLink('windowStage') windowStage: window.WindowStage | undefined = AppStorage.get('windowStage');
     dialogControllerConfirm: CustomDialogController = new CustomDialogController({
       builder: AlertDialog({
         primaryTitle: 'Warning',
         secondaryTitle: 'Timeout Alert',
         content: 'Screen has been inactive for over 6 seconds.',
         primaryButton: {
           value: 'Cancel',
           action: () => {
           },
         },
         secondaryButton: {
           value: 'Confirm',
           role: ButtonRole.ERROR,
           action: () => {
             console.info('Callback when the second button is clicked')
           }
         },
       }),
     })

     aboutToAppear(): void {
       let windowClass: window.Window | undefined = undefined;
       if (this.windowStage){
         this.windowStage.getMainWindow((err: BusinessError, data) => {
           const errCode: number = err.code;
           if (errCode) {
             console.error(`Failed to obtain the main window. Cause code: ${err.code}, message: ${err.message}`);
             return;
           }
           windowClass = data;
           try {
             windowClass.on('noInteractionDetected', 6, () => {
               console.info('no interaction in 6s');
               this.dialogControllerConfirm.open()
             });
           } catch (exception) {
             console.error(`Failed to register callback. Cause code: ${exception.code}, message: ${exception.message}`);
           }
         })
       } else {
         console.log('err')
       }
     }

     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%')
     }
   }
Enter fullscreen mode Exit fullscreen mode

Effect:

2.gif

Key Takeaway

  • Use on('noInteractionDetected') to detect idle states from physical input inactivity.
  • Display AlertDialog to inform or prompt users when they’ve been idle too long.
  • Trigger this logic during aboutToAppear() to ensure it activates when the component is in view.
  • Enhance user experience by addressing both inactivity and re-engagement effectively.

Written by Mucahid Kincir

Top comments (0)