HarmonyOS NEXT-API19 to get context, get context in class and ability, API migration example - Solve the problem that you can't use the latest version

Use the latest API to get UIContext, context
HarmonyOS is developing rapidly, and in the blink of an eye, API16, modelVersion5.1.1 has arrived.
A lot of APIs were deprecated in 18, so let's take a look at which ones we have
getContext(this)(It has been abandoned)
We need to use UIContext to get the UIContext instance and get the context.
Sample code:
1. In the component:
const uiContext = this.getUIContext()?.getHostContext()//Get the Context
this.getUIContext() //Get a UIContext instance
2. In the class Class (or some utility class .ets file):
const context = AppStorageV2.connect(UIContext, 'uiContext', () => new UIContext())?.getHostContext()
3. In ability: location (write code in onWindowStageCreate under EntryAbility)
windowStage.getMainWindow().then((win) => {
const uiContext = win.getUIContext()//Get a UIContext instance
const Context=uiContext.getHostContext()//Get context
}
Note: Use the example code from the developer documentation
windowStage.getMainWindowSync().getUIContext()
An error will be reported, as follows
Error message:This window state is abnormal.
Please use the method used by the author above (to avoid the error that the program cannot be run)
2. Other API migration examples
1. promptAction.showToast(), the API has been deprecated in the latest version, just use the following example API
//Legacy APIs
promptAction.showToast({ message: 'Triggered' })
//Example of migrating the latest version of an API
promptAction.openToast({ message: 'Triggered' })
2. router.replaceUrl(), the API has been deprecated in the latest version, just use the following example API
//Legacy API (deprecated)
router.replaceUrl({ url: 'pages/Index' })
//Migrate the API to the latest version
this.getUIContext().getRouter().replaceUrl({ url: 'pages/Index' })
3. promptAction.showDialog(), the API has been deprecated in the latest version, just use the following example API
//Legacy API (deprecated)
await promptAction.showDialog({
message: 'Please grant the app basic permissions, otherwise the app may not start properly',
buttons: [{
text: 'OK',
color: 'blue'
}]
})
//Example of migrating the latest version of an API
await AppStorageV2.connect(UIContext, 'uiContext', () => new UIContext())?. getPromptAction().showDialog({
message: 'Please grant the app basic permissions, otherwise the app may not start properly',
buttons: [{
text: 'OK',
color: 'blue'
}]
})
4. The px2vp API has been deprecated in the latest version and migrated to uiContext.px2vp latest API
//Legacy API (deprecated)
px2vp()
//Example of API migration of the new version
this.getUIContext().px2vp()
Subscribe to my newsletter
Read articles from xiao directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
