DEV Community

HarmonyOS
HarmonyOS

Posted on

Click on the message notification to jump to the application page

Read the original article:Click on the message notification to jump to the application page

Problem description

How to add behavioral intent to notifications and redirect to the specified page of the application when sending messages using Notification Kit?

Background knowledge

When publishing a notification, if you expect users to pull up the target application component or publish a public event by clicking the notification bar, you can apply for WantAgent through Ability Kit to encapsulate it in the notification message.

Solution

1- Apply for notification permission in the code:

  enableNotifications() {
    let requestEnableNotificationCallback = (err: BusinessError): void => {
      if (err) {
        hilog.error(0x0000, 'testTag',
          `[ANS] requestEnableNotification failed, code is ${err.code}, message is ${err.message}`);
      } else {
        hilog.info(0x0000, 'testTag', `[ANS] requestEnableNotification success`);
      }
    };
    notificationManager.requestEnableNotification(this.context, requestEnableNotificationCallback);
  }
Enter fullscreen mode Exit fullscreen mode

2- Create WantAgentInfo information and fill in the bundleName and abilityName of the application to be launched (the application can only set its own bundleName and abilityName), then construct a NotificationRequest object and publish a notification:

      Button('click').onClick(() => {
        let wantAgentObj: WantAgent;
        let wantAgentInfo: wantAgent.WantAgentInfo = {
          wants: [
            {
              deviceId: '',
              bundleName: 'com.example.ir_wantagent',
              abilityName: 'EntryAbility',
              action: '',
              entities: [],
              uri: '',
              parameters: {
                targetPage: 'Index2' // Add target page parameters
              }
            }
          ],
          actionType: wantAgent.OperationType.START_ABILITY,
          requestCode: 0,
          wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]
        };
        wantAgent.getWantAgent(wantAgentInfo, (err: BusinessError, data: WantAgent) => {
          if (err) {
            hilog.error(DOMAIN_NUMBER, TAG, `Failed to get want agent. Code is ${err.code}, message is ${err.message}`);
            return;
          }
          hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in getting want agent.');
          wantAgentObj = data;
          // Constructing a NotificationRequest object
          let notificationRequest: notificationManager.NotificationRequest = {
            content: {
              notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
              normal: {
                title: 'Test_Title',
                text: 'Test_Text',
                additionalText: 'Test_AdditionalText',
              },
            },
            id: 6,
            label: 'TEST',
            // Before using wantAgentObj, you need to ensure that it has been assigned a value (that is, step 3 is completed)
            wantAgent: wantAgentObj,
          }
          notificationManager.publish(notificationRequest, (err: BusinessError) => {
            if (err) {
              hilog.error(DOMAIN_NUMBER, TAG,
                `Failed to publish notification. Code is ${err.code}, message is ${err.message}`);
              return;
            }
            hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in publishing notification.');
          });
        });
      })
Enter fullscreen mode Exit fullscreen mode

3- Add methods in the EntryAbility.ets file to implement the target UIAbility hot start and target UIAbility cold start to obtain the WantAgentInfo information after clicking the message notification and jump to the specified page.

  • Hot start code, when the application is started, click the message notification to enter the specified page:
  //热启动
  onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    // Get parameters through want.parameters
    const targetPage = want.parameters?.targetPage;
    console.info(`onNewWant Received parameter: ${targetPage}`)
    // Execute logic based on parameters (such as navigating to a page)
    if (targetPage === 'Index2') {
      // Navigate to Index2 page
      router.pushUrl({
        url: 'pages/Index2'
      });
    }
  }
Enter fullscreen mode Exit fullscreen mode
  • Cold start code, when the application starts, click the message notification to enter the specified page:
 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
    this.funcAbilityWant = want;
  }
  onWindowStageCreate(windowStage: window.WindowStage): void {
    let url = 'pages/Index';
    if (this.funcAbilityWant?.parameters?.targetPage === 'Index2') {
      url = 'pages/Index2'; //You need to add a new page Index2 to simulate the navigate action
    }
    console.info(`url:${url}`)
    windowStage.loadContent(url, (err) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');
    });
  }
Enter fullscreen mode Exit fullscreen mode

4- Steps to add a new Index2 page: right-click the Pages folder in the project, select New, then click Page and finally click New Page, enter Index2 to create the Page page file Index2.ets.
5- Steps to simulate clicking a message to jump to the page:

  • Cold start: After sending the message, terminate the application on the multitasking page, and then click the message to jump to the application's specified page Index2.

  • Hot start: After sending the message, return the application to the background, and then click the message to jump to the application's specified page Index2.

The complete code is as follows:

Index.ets code:

import { common, wantAgent, WantAgent } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { notificationManager } from '@kit.NotificationKit';
const TAG: string = '[PublishOperation]';
const DOMAIN_NUMBER: number = 0xFF00;
@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  private context = getContext(this) as common.UIAbilityContext;
  enableNotifications() {
    let requestEnableNotificationCallback = (err: BusinessError): void => {
      if (err) {
        hilog.error(0x0000, 'testTag',
          `[ANS] requestEnableNotification failed, code is ${err.code}, message is ${err.message}`);
      } else {
        hilog.info(0x0000, 'testTag', `[ANS] requestEnableNotification success`);
      }
    };
    notificationManager.requestEnableNotification(this.context, requestEnableNotificationCallback);
  }
  aboutToAppear(): void {
    this.enableNotifications()
  }
  build() {
    Column() {
      Button('click').onClick(() => {
        let wantAgentObj: WantAgent;
        let wantAgentInfo: wantAgent.WantAgentInfo = {
          wants: [
            {
              deviceId: '',
              bundleName: 'com.example.ir_wantagent',
              abilityName: 'EntryAbility',
              action: '',
              entities: [],
              uri: '',
              parameters: {
                targetPage: 'Index2' // Add target page parameters
              }
            }
          ],
          actionType: wantAgent.OperationType.START_ABILITY,
          requestCode: 0,
          wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]
        };
        wantAgent.getWantAgent(wantAgentInfo, (err: BusinessError, data: WantAgent) => {
          if (err) {
            hilog.error(DOMAIN_NUMBER, TAG, `Failed to get want agent. Code is ${err.code}, message is ${err.message}`);
            return;
          }
          hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in getting want agent.');
          wantAgentObj = data;
          // Constructing a NotificationRequest object
          let notificationRequest: notificationManager.NotificationRequest = {
            content: {
              notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
              normal: {
                title: 'Test_Title',
                text: 'Test_Text',
                additionalText: 'Test_AdditionalText',
              },
            },
            id: 6,
            label: 'TEST',
            wantAgent: wantAgentObj,
          }
          notificationManager.publish(notificationRequest, (err: BusinessError) => {
            if (err) {
              hilog.error(DOMAIN_NUMBER, TAG,
                `Failed to publish notification. Code is ${err.code}, message is ${err.message}`);
              return;
            }
            hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in publishing notification.');
          });
        });
      })
    }
    .width("100%")
    .height("100%")
    .justifyContent(FlexAlign.Center)
  }
}
Enter fullscreen mode Exit fullscreen mode
  • EntryAbility.ets code:
import { AbilityConstant, ConfigurationConstant, UIAbility, Want, WantAgent } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { router, window } from '@kit.ArkUI';
export default class EntryAbility extends UIAbility {
  funcAbilityWant: Want | undefined = undefined;
  uiContext: UIContext | undefined = undefined;
  // cold start
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
    this.funcAbilityWant = want;
  }
  //hot start
  onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    // Get parameters through want.parameters
    const targetPage = want.parameters?.targetPage;
    console.info(`onNewWant Received parameter: ${targetPage}`)
    // Execute logic based on parameters (such as navigating to a page)
    if (targetPage === 'Index2') {
      // Navigate to Index2 page
      router.pushUrl({
        url: 'pages/Index2'
      });
    }
  }
  onDestroy(): void {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
  }
  onWindowStageCreate(windowStage: window.WindowStage): void {
    let url = 'pages/Index';
    if (this.funcAbilityWant?.parameters?.targetPage === 'Index2') {
      url = 'pages/Index2';
    }
    console.info(`url:${url}`)
    windowStage.loadContent(url, (err) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');
    });
  }
  onWindowStageDestroy(): void {
    // Main window is destroyed, release UI related resources
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
  }
  onForeground(): void {
    // Ability has brought to foreground
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
  }
  onBackground(): void {
    // Ability has back to background
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
  }
}
Enter fullscreen mode Exit fullscreen mode

Written by Merve Yonetci

Top comments (0)