Compare commits

...

13 Commits

Author SHA1 Message Date
4cb3badb4d array demo 2024-09-25 19:23:07 +08:00
9010489037 add convert 2024-09-13 10:18:33 +08:00
3a4338c99a add rest api 2024-09-11 19:27:24 +08:00
ed6cbec7c9 update scheme open alipay 2024-09-11 15:09:21 +08:00
7bd741a8a0 add location helper 2024-09-06 17:35:31 +08:00
15223b7de4 add location helper 2024-09-06 17:05:31 +08:00
7f9c4bc663 fix warning 2024-09-06 15:36:19 +08:00
bdfab3ab29 add location 2024-09-05 20:34:48 +08:00
ff8c5714d9 ini myapp and review rest api 2024-08-27 19:11:26 +08:00
58ee459459 添加设置语言demo,优化逻辑 2024-08-26 17:05:01 +08:00
f30b7036d6 添加设置语言demo 2024-08-26 16:54:34 +08:00
1654669845 修复编译脚本,支持编译 x86 和 arm 2024-07-15 15:09:09 +08:00
0cfbbb8065 增加Res 类 2024-07-05 14:27:49 +08:00
43 changed files with 843 additions and 150 deletions

View File

@@ -2,7 +2,7 @@
"string": [ "string": [
{ {
"name": "app_name", "name": "app_name",
"value": "HM4Demo" "value": "HMDemo"
} }
] ]
} }

View File

@@ -1,8 +1,11 @@
import { AbilityConstant, AbilityStage, Configuration, Want } from '@kit.AbilityKit'; import { AbilityConstant, AbilityStage, Configuration, Want } from '@kit.AbilityKit';
class HMDemoAbilityStage extends AbilityStage { const TAG = '[AbilityStage]';
export default class AppAbilityStage extends AbilityStage {
onCreate(): void { onCreate(): void {
console.log(TAG, "onCreate")
} }
// onAcceptWant(want: Want): string { // onAcceptWant(want: Want): string {

View File

@@ -0,0 +1,43 @@
import { Context } from '@ohos.arkui.UIContext';
import { window } from '@kit.ArkUI';
import { abilityAccessCtrl } from '@kit.AbilityKit';
import { Log } from '@devwiki/base';
import { BusinessError } from '@kit.BasicServicesKit';
const TAG = '[MyApp]'
export class MyApp {
static appContext: Context;
static uiContext: UIContext;
static mainWindow: window.Window;
static uiAbilityContext: Context;
private constructor() {
}
static initAbility(uiAbilityContext: Context) {
MyApp.uiAbilityContext = uiAbilityContext;
MyApp.appContext = uiAbilityContext.getApplicationContext();
}
static initWindow(window: window.Window) {
MyApp.mainWindow = window;
MyApp.uiContext = window.getUIContext();
}
static requestBasicPermission() {
let atManager = abilityAccessCtrl.createAtManager();
try {
atManager.requestPermissionsFromUser(MyApp.uiAbilityContext,
['ohos.permission.INTERNET'])
.then((data) => {
Log.info(TAG, 'requestBasicPermission, data:' + data.permissions[0])
})
.catch((err: BusinessError) => {
Log.info(TAG, 'requestBasicPermission, error:' + err.message)
})
} catch (err) {
}
}
}

View File

@@ -1,6 +1,9 @@
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit'; import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI'; import { window } from '@kit.ArkUI';
import { MyApp } from '../MyApp';
const TAG = '[AppAbility]'
export default class AppAbility extends UIAbility { export default class AppAbility extends UIAbility {
constructor() { constructor() {
@@ -10,24 +13,26 @@ export default class AppAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
MyApp.initAbility(this.context);
MyApp.requestBasicPermission();
} }
onDestroy(): void { onDestroy(): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy'); hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
} }
onWindowStageCreate(windowStage: window.WindowStage): void { onWindowStageCreate(windowStage: window.WindowStage): void {
// Main window is created, set main page for this ability // Main window is created, set main page for this ability
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
windowStage.loadContent('pages/Index', (err, data) => {
windowStage.loadContent('pages/Index', (err, data) => { if (err.code) {
if (err.code) { hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); return;
return; }
} MyApp.initWindow(windowStage.getMainWindowSync());
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
}); });
} }
onWindowStageDestroy(): void { onWindowStageDestroy(): void {
// Main window is destroyed, release UI related resources // Main window is destroyed, release UI related resources

View File

@@ -6,10 +6,11 @@ import { BusinessError } from '@ohos.base';
import { Log } from '@devwiki/base'; import { Log } from '@devwiki/base';
import { BaseLocalStorage, ScreenUtil } from '@devwiki/base'; import { BaseLocalStorage, ScreenUtil } from '@devwiki/base';
import { HomeItem, HomeItemGroup } from '../model/Home'; import { HomeItem, HomeItemGroup } from '../model/Home';
import { Context } from '@kit.AbilityKit'; import { MyApp } from '../MyApp';
import { Calculator } from '@devwiki/hmcalculate';
import('./animation/LoadingPage') import './animation/LoadingPage'
import './animation/ScaleRotatePage'
import { PageName } from './PageName';
@Entry @Entry
@Component @Component
@@ -30,7 +31,8 @@ struct Index {
name: 'Component', name: 'Component',
items: [ items: [
{name: 'InputPage', page: 'pages/component/InputPage'}, {name: 'InputPage', page: 'pages/component/InputPage'},
{name: 'ToastPage', page: 'pages/component/ToastPage'} {name: 'ToastPage', page: 'pages/component/ToastPage'},
{name: 'TextPage', page: 'pages/component/TextPage'}
] ]
}, },
// 布局 // 布局
@@ -47,6 +49,7 @@ struct Index {
items: [ items: [
{ name: 'CompTransition', page: 'pages/animation/CompTransitionPage'}, { name: 'CompTransition', page: 'pages/animation/CompTransitionPage'},
{ name: 'Loading', page: 'pages/animation/LoadingPage'}, { name: 'Loading', page: 'pages/animation/LoadingPage'},
{ name: 'ScaleRotatePage', page: PageName.ScaleRotatePage },
] ]
}, },
// 多媒体 // 多媒体
@@ -61,14 +64,22 @@ struct Index {
name: 'System', name: 'System',
items: [ items: [
{name: "Scheme", page: 'pages/system/SchemePage'}, {name: "Scheme", page: 'pages/system/SchemePage'},
{name: "MVVM", page: 'pages/mvvm/HomePage'} {name: "MVVM", page: 'pages/mvvm/HomePage'},
{name: "ArrayBind", page: 'pages/mvvm/ArrayBindPage'},
{name: "SetLanguage", page: 'pages/system/SetLanguagePage'}
]
},
{
name: 'Map',
items: [
{name: 'Map', page: 'pages/map/MapPage'}
] ]
} }
]; ];
aboutToAppear(): void { aboutToAppear(): void {
ScreenUtil.getInstance().initScreenSize(); ScreenUtil.getInstance().initScreenSize(MyApp.appContext);
BaseLocalStorage.getInstance().init(getContext(this)); BaseLocalStorage.getInstance().init(MyApp.appContext);
} }
onPageShow(): void { onPageShow(): void {
@@ -106,17 +117,17 @@ struct Index {
}).then((result: promptAction.ShowDialogSuccessResponse) => { }).then((result: promptAction.ShowDialogSuccessResponse) => {
if (result.index === 0) { if (result.index === 0) {
// 用户点击了“取消”按钮 // 用户点击了“取消”按钮
Log.i('User canceled the operation.'); Log.info('User canceled the operation.');
} else if (result.index === 1) { } else if (result.index === 1) {
// 用户点击了“确认”按钮 // 用户点击了“确认”按钮
Log.i('User confirmed the operation.'); Log.info('User confirmed the operation.');
// 调用router.back()方法,返回上一个页面 // 调用router.back()方法,返回上一个页面
router.back(); router.back();
} }
}).catch((err: Error) => { }).catch((err: Error) => {
let message = (err as BusinessError).message let message = (err as BusinessError).message
let code = (err as BusinessError).code let code = (err as BusinessError).code
Log.i(`Invoke showDialog failed, code is ${code}, message is ${message}`); Log.info(`Invoke showDialog failed, code is ${code}, message is ${message}`);
}) })
return true; return true;
} }
@@ -143,7 +154,11 @@ struct Index {
Divider().margin({ top: 2 }); Divider().margin({ top: 2 });
}.onClick(() => { }.onClick(() => {
if (item.page) { if (item.page) {
this.getUIContext().getRouter().pushUrl({url: item.page }) if (item.page.startsWith('pages/')) {
this.getUIContext().getRouter().pushUrl({url: item.page })
} else {
this.getUIContext().getRouter().pushNamedRoute({name: item.page })
}
} }
}) })
} }

View File

@@ -0,0 +1,5 @@
export enum PageName {
ScaleRotatePage = 'animation/ScaleRotatePage'
}

View File

@@ -4,7 +4,7 @@ import { curves } from '@kit.ArkUI';
@Entry({ routeName: PageName.loadingPage }) @Entry({ routeName: PageName.loadingPage })
@Component @Component
export struct LoadingPage { struct LoadingPage {
@State animate: boolean = false; @State animate: boolean = false;
@State rotateValue: number = 0; @State rotateValue: number = 0;

View File

@@ -0,0 +1,67 @@
import { PageName } from '../PageName';
@Component
@Entry({routeName: PageName.ScaleRotatePage})
struct ScaleRotatePage {
@State orderId:string = ''
@State rootJustifyContent: FlexAlign = FlexAlign.Start
@State showQRAnimation: boolean= false
@State qrColumnHeight: Length = ''
@State qrJustifyContent: FlexAlign = FlexAlign.Start
@State showBarcodeAnimation : boolean = false;
@State barcodeHeight: Length = ''
@State barcodeAngle: number = 0
@Builder
ScanBarCodeDialog(){
}
private ScanBarCodeDialogController: CustomDialogController = new CustomDialogController({
builder: this.ScanBarCodeDialog,
autoCancel: true,
alignment: DialogAlignment.Center,
customStyle: true,
openAnimation: {
}
})
build() {
Column(){
Text('Title')
Column(){
Image($r('app.media.ic_eye_off')).width(200).height(200).onClick(() =>{
})
Text('Order Id:' + this.orderId).visibility(this.showQRAnimation ? Visibility.Visible : Visibility.None)
}.width('100%').visibility(this.showBarcodeAnimation ? Visibility.None : Visibility.Visible)
.animation({
duration: 1000
})
Text('Order Id:' + this.orderId).visibility(this.showQRAnimation || this.showBarcodeAnimation ? Visibility.None : Visibility.Visible)
Column(){
Text('Order Id:' + this.orderId).visibility(this.showBarcodeAnimation ? Visibility.Visible : Visibility.None)
Image($r('app.media.ic_eye_off')).width(400).height(100).onClick(() =>{
})
}.visibility(this.showQRAnimation ? Visibility.None : Visibility.Visible)
.rotate({ centerX: '50%', centerY: '50%', angle: this.barcodeAngle})
.animation({
duration: 1000
})
}.width('100%').height('100%').alignItems(HorizontalAlign.Center).justifyContent(this.rootJustifyContent)
}
}

View File

@@ -2,7 +2,7 @@ import { CommonRes } from '@devwiki/common_ui/Index'
@Entry @Entry
@Component @Component
export struct SVGPage { struct SVGPage {
build() { build() {
Column() { Column() {
Text().width(96).height(96).backgroundColor($r('app.media.ic_eye_off')) Text().width(96).height(96).backgroundColor($r('app.media.ic_eye_off'))

View File

@@ -3,6 +3,27 @@
@Component @Component
struct TextPage { struct TextPage {
@State states: string[] = ['1', '2', '3', '4'];
build() { build() {
Column(){
Button('Change').onClick(() => {
this.states[3] = '999'
})
List(){
ForEach(this.states, (state: string, index: number) => {
ListItem(){
Column(){
Text(state).width(this.getWidth(state, index))
Divider().width('90%')
}
}
})
}.height('100%').width('100')
}.width('100%')
}
getWidth(title: string, index: number): Length {
return 0;
} }
} }

View File

@@ -12,7 +12,7 @@ class ToastViewMode {
@Entry @Entry
@Component @Component
export struct ToastPage { struct ToastPage {
@Provide toastVM: ToastViewMode = new ToastViewMode(); @Provide toastVM: ToastViewMode = new ToastViewMode();

View File

@@ -3,7 +3,7 @@ import { ComponentConst } from '@devwiki/common_ui/Index'
@Entry @Entry
@Component @Component
export struct RelativeContainerPage { struct RelativeContainerPage {
build() { build() {
RelativeContainer() { RelativeContainer() {
@@ -12,7 +12,7 @@ export struct RelativeContainerPage {
top: { anchor: ComponentConst.ContainerId, align: VerticalAlign.Top }, top: { anchor: ComponentConst.ContainerId, align: VerticalAlign.Top },
left: { anchor: ComponentConst.ContainerId, align: HorizontalAlign.Start }, left: { anchor: ComponentConst.ContainerId, align: HorizontalAlign.Start },
bottom: { anchor: ComponentConst.ContainerId, align: VerticalAlign.Bottom } bottom: { anchor: ComponentConst.ContainerId, align: VerticalAlign.Bottom }
}).id('left_menu') }).id('left_menu0')
Button(){ Button(){
Text("2222").height(64) Text("2222").height(64)
@@ -21,7 +21,7 @@ export struct RelativeContainerPage {
top: { anchor: ComponentConst.ContainerId, align: VerticalAlign.Top }, top: { anchor: ComponentConst.ContainerId, align: VerticalAlign.Top },
right: { anchor: ComponentConst.ContainerId, align: HorizontalAlign.End }, right: { anchor: ComponentConst.ContainerId, align: HorizontalAlign.End },
bottom: { anchor: ComponentConst.ContainerId, align: VerticalAlign.Bottom } bottom: { anchor: ComponentConst.ContainerId, align: VerticalAlign.Bottom }
}).id('right_menu') }).id('right_menu0')
}.height(64).width('100%').backgroundColor(Color.Red) }.height(64).width('100%').backgroundColor(Color.Red)
} }
} }

View File

@@ -0,0 +1,58 @@
import { abilityAccessCtrl, bundleManager, common, PermissionRequestResult, Permissions } from '@kit.AbilityKit';
import { geoLocationManager } from '@kit.LocationKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { LocationHelper } from '../../utils/LocationHelper';
@Component
@Entry({routeName: 'MapPage'})
struct MapPage {
@State isShowLocationPopup: boolean = false
appName: string = ''
@State isLocationPermission: boolean = false;
@State locText: string = ''
locationHelper: LocationHelper = new LocationHelper(getContext(this) as common.UIAbilityContext);
@Builder
locationViewBuilder() {
Row() {
Text('开启定位权限').fontSize(15);
Button('去开启')
.type(ButtonType.Normal)
.height(24)
.borderRadius(12)
.width(60)
.backgroundColor(Color.Red)
.onClick(() => {
this.locationHelper.getLocationAddress( 31.12, 121.11, 1, (error: BusinessError, data: geoLocationManager.GeoAddress[]) => {
})
})
SymbolGlyph($r('sys.symbol.xmark')).width(24).height(24).borderRadius(12).onClick(() => {
this.isShowLocationPopup = false;
})
}
.height(40)
.alignItems(VerticalAlign.Center)
.padding(5)
.position({ x: 7, y: 50 })
.zIndex(999)
.backgroundColor('#123333')
.borderRadius(10)
.opacity(0.7)
}
build() {
Column(){
this.locationViewBuilder();
Text(this.locText);
}.width('100%').height('100%')
}
aboutToAppear(): void {
this.locationHelper.requestPermissionsFromUser((allowScope: boolean, allowPrecision: boolean) => {
})
}
}

View File

@@ -137,7 +137,7 @@ async function release() {
@Entry @Entry
@Component @Component
export struct AudioPlayerPage { struct AudioPlayerPage {
build() { build() {
} }

View File

@@ -0,0 +1,25 @@
@Entry
@Component
export struct ArrayBindPage {
@State firstDatas: string[] = ["1"];
@State secondDatas: string[] = ["2"]
build() {
Column(){
Text(this.firstDatas[0]);
Text(this.secondDatas[0]).margin({top: 16})
Button("Change").margin({top: 16}).onClick(() => {
let first = this.firstDatas;
this.changeFirstIndex(first);
this.changeFirstIndex(this.secondDatas);
})
}.width('100%').height('100%')
}
changeFirstIndex(datas: string[]) {
datas[0] = '111'
}
}

View File

@@ -1,9 +1,9 @@
import { Emitter, EmitterItem } from '@devwiki/base'; import { Emitter, EmitterItem } from '@devwiki/base';
import { Toast } from '../../../../../../common_ui/src/main/ets/utils/Toast'; import { Toast } from '@devwiki/common_ui';
@Entry @Entry
@Component @Component
export struct HomePage { struct HomePage {
@Provide tv1ViewModel: TabView1ViewModel = new TabView1ViewModel(); @Provide tv1ViewModel: TabView1ViewModel = new TabView1ViewModel();
@Provide tv2ViewModel: TabView2ViewModel = new TabView2ViewModel(); @Provide tv2ViewModel: TabView2ViewModel = new TabView2ViewModel();

View File

@@ -0,0 +1,45 @@
import { BusinessError } from '@ohos.base';
export class APIQuery extends Map<string, string|number|boolean> { }
export interface APIHeader {
[key: string]: string;
}
export enum APIRequestMethod {
GET, POST, PUT, DELETE
}
export class APIRequest {
url: string = "";
method: APIRequestMethod = APIRequestMethod.POST;
extraData?: string | Object | ArrayBuffer;
header?: APIHeader[];
}
export class APIResult<T> {
httpCode: number;
businessError?: BusinessError;
error?: APIError;
data?: T;
}
export interface APIError{
errors: string[];
message: string;
url: string;
}
export interface Organization {
id: number;
name: string;
full_name: string;
email: string;
avatar_url: string;
description: string;
website: string;
location: string;
visibility: string;
repo_admin_change_team_access: boolean;
username: string;
}

View File

@@ -0,0 +1,123 @@
import http from '@ohos.net.http';
import { Log } from '@devwiki/base/Index';
import { APIError, APIHeader, APIQuery, APIRequestMethod, Organization } from './APIModel';
import { APIRequest } from './APIModel';
import { APIResult } from './APIModel';
import axios from '@ohos/axios';
import { Axios } from '@ohos/axios';
const TAG = '[RestAPI]'
export class RestAPI {
private baseUrl: string ='https://gitea.com/api/v1';
private readonly timeout = 10000;
private baseQuery: string = '?=0';
private defaultHeaders: APIHeader[] = [
{ "connection" : "keep-alive" },
{ 'accept-encoding' : 'gzip, deflate, br, zstd' },
{ 'accept-language' : 'zh-CN,zh;q=0.9,en;q=0.8' }
];
public getAllOrganizations(callback: (result: APIResult<Organization[]>) => void) {
let path = '/orgs'
let url = this.getUrl(path);
Log.info(TAG, 'getOrgByName url:' + url);
this.request({
url: url,
method: APIRequestMethod.GET
}, callback);
}
public getAllOrganizationsByPage(page: number, limit: number, callback: (result: APIResult<Organization[]>) => void) {
let path = '/orgs'
let extraQuery = new APIQuery()
extraQuery.set('page', page);
extraQuery.set('limit', limit);
let url = this.getUrl(path, extraQuery);
Log.info(TAG, 'getOrgByName url:' + url);
this.request({
url: url,
method: APIRequestMethod.GET
}, callback);
}
public getOrgByName(name: string, callback: (result: APIResult<Organization>) => void) {
let path = `/orgs/${name}`;
let url = this.getUrl(path);
Log.info(TAG, 'getOrgByName url:' + url);
this.request({
url: url,
method: APIRequestMethod.GET
}, callback);
}
request<T>(apiReq: APIRequest, callback: (result: APIResult<T>) => void) {
Log.info(TAG, 'request, url:' + apiReq.url)
let httpRequest = http.createHttp();
let option:http.HttpRequestOptions = this.createHttpRequestOption(apiReq);
httpRequest.request(apiReq.url, option, (error, resp) =>{
let result: APIResult<T> = new APIResult();
if (!error) {
Log.info(TAG, 'result, httpCode:' + result.httpCode + ', data:' + resp.result?.toString())
result.httpCode = resp.responseCode;
try {
if (resp.responseCode == http.ResponseCode.OK) {
result.data = JSON.parse(resp.result?.toString()) as T
} else {
result.error = JSON.parse(resp.result?.toString()) as APIError;
}
} catch (e) {
Log.error(TAG, 'result json parse error:' + e)
}
callback?.(result);
} else {
result.businessError = error;
callback?.(result);
Log.error(TAG, `request ${apiReq.url} failed, code:${error.code}, message:${error.message}`)
}
httpRequest.destroy();
});
}
private createHttpRequestOption(apiReq: APIRequest): http.HttpRequestOptions{
let headers: APIHeader[] = this.defaultHeaders;
if (apiReq.header) {
apiReq.header.forEach((header) =>{
headers.push(header);
})
}
let method: http.RequestMethod = http.RequestMethod.GET;
if (apiReq.method == APIRequestMethod.POST) {
method = http.RequestMethod.POST;
} else if (apiReq.method == APIRequestMethod.PUT) {
method = http.RequestMethod.PUT;
} else if (apiReq.method == APIRequestMethod.DELETE) {
method = http.RequestMethod.DELETE;
} else {
method = http.RequestMethod.GET;
}
return {
method: method,
extraData : apiReq.extraData,
readTimeout : this.timeout,
connectTimeout: this.timeout,
expectDataType: http.HttpDataType.STRING,
header: headers,
usingProtocol: http.HttpProtocol.HTTP1_1
};
}
private getUrl(path: string, extraQuery?: APIQuery): string {
let url = `${this.baseUrl}${path}${this.baseQuery}`;
if (extraQuery) {
for (let key of extraQuery.keys()) {
url += `&${key}=${extraQuery.get(key)}`
}
}
Log.debug(TAG, `get url, path: ${path}, url:${url}`)
return url;
}
}

View File

@@ -1,44 +1,95 @@
import { Log } from '@devwiki/base/Index'; import { Log } from '@devwiki/base/Index';
import axios, { AxiosError, AxiosResponse } from '@ohos/axios' import axios, { AxiosError, AxiosResponse } from '@ohos/axios'
import http from '@ohos.net.http';
import { RestAPI } from './RestAPI';
import { Organization } from './APIModel';
import { convertxml, util } from '@kit.ArkTS';
const TAG = '[RestAPIPage]'
@Entry({routeName: "RestAPIPage"}) @Entry({routeName: "RestAPIPage"})
@Component @Component
export struct RestAPIPage { struct RestAPIPage {
@State viewModel: RestAPIViewModel = new RestAPIViewModel(); @State viewModel: RestAPIViewModel = new RestAPIViewModel();
build() { build() {
Row() { Column() {
Flex({ Flex({
justifyContent: FlexAlign.SpaceBetween justifyContent: FlexAlign.Start,
direction: FlexDirection.Column,
alignItems: ItemAlign.Center
}) { }) {
Button("Get").onClick(() =>{
this.viewModel.getServerVersion(); Refresh({
refreshing: $$this.viewModel.refreshing,
}){
List(){
ForEach(this.viewModel.orsg, (org: Organization, index: number) =>{
ListItem(){
Row() {
Image(org.avatar_url).width(36).height(36).objectFit(ImageFit.Contain)
Text(org.name)
}.justifyContent(FlexAlign.Start).alignItems(VerticalAlign.Center).height(48)
}
})
}.width('100%').height('100%').layoutWeight(1)
}.pullToRefresh(true)
.onRefreshing(() =>{
this.viewModel.getAllOrgs();
}) })
Text(this.viewModel.serverVersion).backgroundColor(Color.Blue).flexGrow(1); Button("GetByHttp").onClick(() =>{
} this.viewModel.getServerVersionByHttp();
}.justifyContent(FlexAlign.Start).alignItems(VerticalAlign.Center).width('80%').backgroundColor(Color.Green) }).margin({top: 20})
}.width('80%')
}.width('100%')
} }
} }
class RestAPIViewModel { class RestAPIViewModel {
serverVersion: string = '123' orsg: Organization[] = []
refreshing: boolean = false;
async getServerVersion() { private restAPI: RestAPI = new RestAPI();
await axios({
method: "post", getAllOrgs() {
url: 'https://music.devwiki.net/rest/ping.view?v=1.16.1&c=myapp&f=json' this.restAPI.getAllOrganizations((result) => {
}).then((response: AxiosResponse) => { if (result.data) {
if (response.status == 200) { this.orsg = result.data;
let version:string = response.data['subsonic-response']['serverVersion'];
this.serverVersion = version;
Log.i(`serverVersion: ${this.serverVersion}`)
} }
}).catch((error: AxiosError) => { this.refreshing = false;
Log.e(error.message);
}) })
} }
getServerVersionByHttp() {
let request = http.createHttp();
let header: Map<string, string> = new Map();
request.request('https://qt.gtimg.cn/q=s_sh000001', {
header: {
'Content-Type': 'text/html; charset=GBK'
},
expectDataType: http.HttpDataType.ARRAY_BUFFER
}).then(res => {
let data = this.gbkToUTF8(res.result as ArrayBuffer);
Log.info(res.responseCode.toString());
})
}
gbkToUTF8(content: ArrayBuffer): string {
let textDecoderOptions: util.TextDecoderOptions = {
fatal: false,
ignoreBOM : true
}
let decodeWithStreamOptions: util.DecodeWithStreamOptions = {
stream: true
}
let textDecoder = util.TextDecoder.create('gbk', textDecoderOptions);
let retStr = textDecoder.decodeWithStream( new Uint8Array(content) , decodeWithStreamOptions);
return retStr;
}
} }

View File

@@ -26,10 +26,10 @@ class TcpSocket {
let message = String.fromCharCode(messages); let message = String.fromCharCode(messages);
messageView += message; messageView += message;
} }
Log.i(`receive message: ${messageView}`) Log.info(`receive message: ${messageView}`)
}) })
this.tcp.on('error', (error) => { this.tcp.on('error', (error) => {
Log.i(`tcp error: ${error.message}`) Log.info(`tcp error: ${error.message}`)
}) })
} }
@@ -40,19 +40,19 @@ class TcpSocket {
this.tcp.bind(address) this.tcp.bind(address)
this.tcp.connect(this.connectOptions, (error) => { this.tcp.connect(this.connectOptions, (error) => {
if (error) { if (error) {
Log.e(`connect fail: ${error.message}`); Log.error(`connect fail: ${error.message}`);
return; return;
} }
Log.i('connect success') Log.info('connect success')
}) })
} }
send(text: string) { send(text: string) {
let option: socket.TCPSendOptions = { data: text} let option: socket.TCPSendOptions = { data: text}
this.tcp.send(option).then(() => { this.tcp.send(option).then(() => {
Log.i(`send data: ${text} success`) Log.info(`send data: ${text} success`)
}).catch((error: BusinessError) => { }).catch((error: BusinessError) => {
Log.e(`send data: ${text} error: ${error.message}`) Log.error(`send data: ${text} error: ${error.message}`)
}) })
} }
} }
@@ -60,7 +60,7 @@ class TcpSocket {
@Component @Component
@Entry @Entry
export struct TcpSocketPage { struct TcpSocketPage {
tcpSocket: TcpSocket = new TcpSocket(); tcpSocket: TcpSocket = new TcpSocket();

View File

@@ -3,7 +3,7 @@ import { common, Want } from '@kit.AbilityKit';
@Component @Component
@Entry @Entry
export struct SchemePage { struct SchemePage {
build() { build() {
Column() { Column() {
TitleBar({ TitleBar({
@@ -13,18 +13,22 @@ export struct SchemePage {
} }
}) })
Button("Open").width(120).height(36).onClick(() => { Button("OpenApp").width(120).height(36).onClick(() => {
this.openScheme() this.openScheme('alipays://platformapi/startapp?appId=20000001')
}).margin({ top: 48 })
Button("OpenStore").width(120).height(36).onClick(() => {
this.openScheme('store://appgallery.huawei.com/app/detail?id=com.alipay.mobile.client')
}).margin({ top: 48 }) }).margin({ top: 48 })
} }
} }
openScheme() { openScheme(uri: string) {
let context = getContext(this) as common.UIAbilityContext; let context = getContext(this) as common.UIAbilityContext;
let wantInfo: Want = { let wantInfo: Want = {
action: 'ohos.want.action.viewData', // action: 'ohos.want.action.viewData',
entities: ['entity.system.browsable'], // entities: ['entity.system.browsable'],
uri: 'https://devwiki.net' uri: uri
} }
context.startAbility(wantInfo); context.startAbility(wantInfo);
} }

View File

@@ -0,0 +1,48 @@
import { TitleBar } from '@devwiki/common_ui';
import { i18n } from '@kit.LocalizationKit';
import { Log } from '@devwiki/base';
const TAG = '[SetLanguagePage]'
@Entry
@Component
struct SetLanguagePage {
private readonly languageGroup = "languageGroup"
@State selectedLanguage: string = 'zh-Hans';
aboutToAppear(): void {
let languages:string[] = i18n.System.getSystemLanguages();
languages.forEach((value, index) => {
Log.info(TAG, `${index.toString()}:${value}`)
})
}
build() {
Column() {
TitleBar({
title: $r('app.string.set_language_title')
});
Row() {
Text('简体中文');
Radio({ group: this.languageGroup, value: 'zh-Hans' }).checked(this.selectedLanguage == 'zh-Hans')
.onChange(isChecked => {
if (isChecked) {
i18n.System.setAppPreferredLanguage('zh-Hans')
this.selectedLanguage = 'zh-Hans'
}
});
}
Row() {
Text('英文');
Radio({ group: this.languageGroup, value: 'en-US' }).checked(this.selectedLanguage == 'en-US')
.onChange(isChecked => {
if (isChecked) {
i18n.System.setAppPreferredLanguage('en-US')
this.selectedLanguage = 'en-US'
}
});
}
}.width('100%').height('100%')
}
}

View File

@@ -1,7 +1,7 @@
@Entry({routeName: "TimerPage"}) @Entry({routeName: "TimerPage"})
@Component @Component
export struct TimerPage { struct TimerPage {
build() { build() {
} }
} }

View File

@@ -5,12 +5,12 @@ import { TitleBar } from '@devwiki/common_ui/src/main/ets/component/TitleBar';
@CustomDialog @CustomDialog
export struct WebPageDialog { export struct WebPageDialog {
@StorageLink(ScreenUtil.isPortraitKey) isPortrait: boolean = true; @StorageLink(ScreenUtil.isPortraitKey) isPortrait: boolean = true;
dialogController: CustomDialogController; dialogController?: CustomDialogController;
build() { build() {
WebPage({ WebPage({
onTitleBarLeftClick: () => { onTitleBarLeftClick: () => {
this.dialogController.close(); this.dialogController?.close();
} }
}).height(this.isPortrait ? '95%' : '90%').width(this.isPortrait ? '100%' : '50%') }).height(this.isPortrait ? '95%' : '90%').width(this.isPortrait ? '100%' : '50%')
} }
@@ -18,7 +18,7 @@ export struct WebPageDialog {
@Entry @Entry
@Component @Component
export struct WebDialogPage { struct WebDialogPage {
dialogController: CustomDialogController = new CustomDialogController({ dialogController: CustomDialogController = new CustomDialogController({
builder: WebPageDialog(), builder: WebPageDialog(),

View File

@@ -0,0 +1,105 @@
import { abilityAccessCtrl, bundleManager, common, PermissionRequestResult, Permissions } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { geoLocationManager } from '@kit.LocationKit';
const locationPermission: Permissions[] = ['ohos.permission.LOCATION', 'ohos.permission.APPROXIMATELY_LOCATION'];
export class LocationHelper {
appInfo: bundleManager.BundleInfo;
context: common.UIAbilityContext;
atManager: abilityAccessCtrl.AtManager;
constructor(context: common.UIAbilityContext) {
this.context = context;
this.atManager = abilityAccessCtrl.createAtManager();
this.appInfo = bundleManager.getBundleInfoForSelfSync(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION) // 获取应用信息
}
checkLocationPermission(callback: (isAllow: boolean) => void) {
let status = this.atManager.checkAccessTokenSync(this.appInfo.appInfo.accessTokenId, locationPermission[0])
callback(status === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED)
}
gotoSystemSetting() {
}
// openLocation(callback:(address: string) => void) {
// let options: AMapLocationOption = {
// priority: geoLocationManager.LocationRequestPriority.FIRST_FIX, //定位优先配置选项
// scenario: geoLocationManager.LocationRequestScenario.UNSET, //定位场景设置
// timeInterval: 2, //定位时间间隔
// distanceInterval: 0, //位置报告距离间隔
// maxAccuracy: 0, //定位精度 单位:米
// allowsBackgroundLocationUpdates: false, //是否允许后台定位
// locatingWithReGeocode: true, //定位是否返回逆地理信息
// reGeocodeLanguage: AMapLocationReGeocodeLanguage.Chinese, //逆地址语言类型
// isOffset: true //是否加偏
// }
// let listener: IAMapLocationListener = {
// onLocationChanged: (location) => {
// this.getLocationAddress(location.latitude, location.longitude, 1, (err, data) => {
// if (err) {
// console.error('getAddressesFromLocation: err=' + JSON.stringify(err));
// }
// if (data) {
// console.log('getAddressesFromLocation: data=' + JSON.stringify(data));
// let loc = data[0].placeName ?? '';
// if (data[0].administrativeArea) {
// loc = loc.replace(data[0].administrativeArea, '')
// }
// if (data[0].subAdministrativeArea) {
// loc = loc.replace(data[0].subAdministrativeArea, '')
// }
// if (data[0].subLocality) {
// loc = loc.replace(data[0].subLocality, '')
// }
// if (data[0].roadName) {
// loc = loc.replace(data[0].roadName, '')
// }
// if (data[0].subRoadName) {
// loc = loc.replace(data[0].subRoadName, '')
// }
// if (data[0].subRoadName && loc === '') {
// loc = data[0].subRoadName?.toString()
// }
// callback(loc);
// }
// });
// }, onLocationError: (error) => {
// console.error(`IAMapLocationListener ${error.errorMsg}:${error.errorCode}`)
// }
// };
// this.locationManger?.setLocationListener(AMapLocationType.Updating, listener) //设置定位信息监听
// this.locationManger?.setLocationOption(AMapLocationType.Updating, options) //设置定位配置项
// this.locationManger?.startUpdatingLocation() //开启连续定位
// }
/**
* 请求定位 allowScope是否允许定位, allowPrecision: 是否允许获取精确位置
* @param callback
*/
requestPermissionsFromUser(callback: (allowScope: boolean, allowPrecision: boolean) => void): void {
this.atManager.requestPermissionsFromUser(this.context, locationPermission)
.then((data: PermissionRequestResult) => {
callback(data.authResults[1] === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED,
data.authResults[0] === abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED);
})
.catch((err: BusinessError) => {
console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`);
})
}
getLocationAddress(latitude: number, longitude: number, maxItems: number, callback:(error: BusinessError, data: geoLocationManager.GeoAddress[]) => void) {
let reverseGeocodeRequest:geoLocationManager.ReverseGeoCodeRequest = {"latitude": latitude, "longitude": longitude, "maxItems": maxItems};
try {
geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => {
callback(err, data);
});
} catch (err) {
console.error("errCode:" + JSON.stringify(err));
}
}
}

View File

@@ -0,0 +1,33 @@
import { pasteboard } from '@kit.BasicServicesKit';
class PasteboardUtil {
static async copyData(data: string, type: CopyDataType) {
try {
if (!data) {
return;
}
let mineType = pasteboard.MIMETYPE_TEXT_PLAIN;
if (type === CopyDataType.URI) {
mineType = pasteboard.MIMETYPE_TEXT_URI;
} else if (type === CopyDataType.HTML) {
mineType = pasteboard.MIMETYPE_TEXT_HTML;
}
const pasteData: pasteboard.PasteData = pasteboard.createData(mineType, data);
const systemPasteboard: pasteboard.SystemPasteboard = pasteboard.getSystemPasteboard();
await systemPasteboard.setData(pasteData);
} catch (err) {
console.error('Failed to set PasteData.');
}
}
}
export enum CopyDataType {
TEXT,
URI,
HTML
}

View File

@@ -4,11 +4,18 @@
"type": "entry", "type": "entry",
"description": "$string:module_desc", "description": "$string:module_desc",
"mainElement": "AppAbility", "mainElement": "AppAbility",
"srcEntry": "./ets/AppAbilityStage.ets",
"deviceTypes": [ "deviceTypes": [
"phone", "phone",
"tablet", "tablet",
"2in1" "2in1"
], ],
"metadata": [
{
"name": "client_id",
"value": "123456789"
}
],
"deliveryWithInstall": true, "deliveryWithInstall": true,
"installationFree": false, "installationFree": false,
"pages": "$profile:main_pages", "pages": "$profile:main_pages",
@@ -36,7 +43,18 @@
], ],
"requestPermissions": [ "requestPermissions": [
{ {
"name" : "ohos.permission.INTERNET" "name": "ohos.permission.LOCATION",
"reason": "$string:location_permission",
"usedScene": {
"when": "inuse"
}
},
{
"name": "ohos.permission.APPROXIMATELY_LOCATION",
"reason": "$string:approximately_location",
"usedScene": {
"when": "inuse"
}
} }
] ]
} }

View File

@@ -11,6 +11,18 @@
{ {
"name": "AppAbility_label", "name": "AppAbility_label",
"value": "HM4Demo" "value": "HM4Demo"
},
{
"name": "set_language_title",
"value": "Set Language"
},
{
"name": "location_permission",
"value": "location_permission"
},
{
"name": "approximately_location",
"value": "approximately_location"
} }
] ]
} }

View File

@@ -18,14 +18,20 @@
"pages/media/PhotoPage", "pages/media/PhotoPage",
"pages/mvvm/HomePage", "pages/mvvm/HomePage",
"pages/mvvm/ArrayBindPage",
"pages/net/TcpSocketPage", "pages/net/TcpSocketPage",
"pages/net/RestAPIPage", "pages/net/RestAPIPage",
"pages/system/SchemePage", "pages/system/SchemePage",
"pages/system/TimerPage", "pages/system/TimerPage",
"pages/system/SetLanguagePage",
"pages/web/WebPage", "pages/web/WebPage",
"pages/web/WebDialogPage" "pages/web/WebDialogPage",
"pages/map/MapPage"
] ]
} }

View File

@@ -11,6 +11,18 @@
{ {
"name": "AppAbility_label", "name": "AppAbility_label",
"value": "HMDemo" "value": "HMDemo"
},
{
"name": "set_language_title",
"value": "Set Language"
},
{
"name": "location_permission",
"value": "location_permission"
},
{
"name": "approximately_location",
"value": "approximately_location"
} }
] ]
} }

View File

@@ -11,6 +11,18 @@
{ {
"name": "AppAbility_label", "name": "AppAbility_label",
"value": "HMDemo" "value": "HMDemo"
},
{
"name": "set_language_title",
"value": "设置语言"
},
{
"name": "location_permission",
"value": "location_permission"
},
{
"name": "approximately_location",
"value": "approximately_location"
} }
] ]
} }

View File

@@ -34,12 +34,12 @@ export class BaseLocalStorage {
let options: dataPreferences.Options = { name: BaseLocalStorage.XY_DP_Name }; let options: dataPreferences.Options = { name: BaseLocalStorage.XY_DP_Name };
this.preferences = dataPreferences.getPreferencesSync(this.context, options); this.preferences = dataPreferences.getPreferencesSync(this.context, options);
} else { } else {
Log.i("LocalStorage is already init.") Log.info("LocalStorage is already init.")
} }
} }
public putData(key: string, value: dataPreferences.ValueType) { public putData(key: string, value: dataPreferences.ValueType) {
Log.i(`put sp data, key:${key}, value:${value}`) Log.info(`put sp data, key:${key}, value:${value}`)
this.preferences?.putSync(key, value); this.preferences?.putSync(key, value);
this.preferences?.flush(); this.preferences?.flush();
} }
@@ -51,7 +51,7 @@ export class BaseLocalStorage {
public getData(key: string, defaultValue: dataPreferences.ValueType): dataPreferences.ValueType | undefined { public getData(key: string, defaultValue: dataPreferences.ValueType): dataPreferences.ValueType | undefined {
let value = this.preferences?.getSync(key, defaultValue); let value = this.preferences?.getSync(key, defaultValue);
Log.i(`get sp data, key:${key}, value:${value}`) Log.info(`get sp data, key:${key}, value:${value}`)
return value; return value;
} }

View File

@@ -2,28 +2,28 @@
import hilog from '@ohos.hilog'; import hilog from '@ohos.hilog';
let domain: number = 0xFF00; let domain: number = 0xFF00;
let prefix: string = 'HM4Demo'; let prefix: string = 'HMDemo';
let format: string = `%{public}s`; let format: string = `%{public}s, %{public}s`;
export class Log { export class Log {
static d(...args: string[]) { static debug(...args: string[]) {
hilog.debug(domain, prefix, format, args); hilog.debug(domain, prefix, format, args);
} }
static i(...args: string[]) { static info(...args: string[]) {
hilog.info(domain, prefix, format, args); hilog.info(domain, prefix, format, args);
} }
static w(...args: string[]) { static warn(...args: string[]) {
hilog.warn(domain, prefix, format, args); hilog.warn(domain, prefix, format, args);
} }
static e(...args: string[]) { static error(...args: string[]) {
hilog.error(domain, prefix, format, args); hilog.error(domain, prefix, format, args);
} }
static f(...args: string[]) { static fatal(...args: string[]) {
hilog.fatal(domain,prefix, format, args); hilog.fatal(domain,prefix, format, args);
} }

View File

@@ -25,11 +25,11 @@ export class ScreenUtil {
return ScreenUtil.instance; return ScreenUtil.instance;
} }
initScreenSize(): void { initScreenSize(context: Context): void {
this.portraitListener.on('change', (result)=> { this.portraitListener.on('change', (result)=> {
AppStorage.setOrCreate(ScreenUtil.isPortraitKey, result.matches) AppStorage.setOrCreate(ScreenUtil.isPortraitKey, result.matches)
}) })
window.getLastWindow(getContext(this)) window.getLastWindow(context)
.then((windowClass: window.Window) => { .then((windowClass: window.Window) => {
let type = window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR; // 以导航条避让为例 let type = window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR; // 以导航条避让为例
let avoidArea = windowClass.getWindowAvoidArea(type); let avoidArea = windowClass.getWindowAvoidArea(type);
@@ -106,7 +106,7 @@ export class ScreenUtil {
} }
setWindowKeepScreenOn(isKeep: boolean) { setWindowKeepScreenOn(isKeep: boolean) {
Log.i(`setWindowKeepScreenOn:${isKeep}`) Log.info(`setWindowKeepScreenOn:${isKeep}`)
window.getLastWindow(getContext(this)) window.getLastWindow(getContext(this))
.then((windowClass: window.Window) => { .then((windowClass: window.Window) => {
windowClass.setWindowKeepScreenOn(isKeep); windowClass.setWindowKeepScreenOn(isKeep);

View File

@@ -7,13 +7,13 @@
"name": "default", "name": "default",
"type": "HarmonyOS", "type": "HarmonyOS",
"material": { "material": {
"certpath": "build_script/sign/HM4Demo.cer", "certpath": "C:\\Users\\zyz\\.ohos\\config\\default_HMDemo_i5yHT0lu8Bugf7Se0a-mWm67_DsSdIYAWNVACnIC98c=.cer",
"storePassword": "0000001B9C6223E8C618FEFD3D871B066F744A4E9C03C09D8ED7E7C7ECE6C1F53A54A6748EC341B960E492", "storePassword": "0000001B17961DDECEBACEACD9CAA1E45CB0BEF5D5A935C253F2AB99644951676ED1B6F102D2B5AD8BCBA2",
"keyAlias": "debugKey", "keyAlias": "debugKey",
"keyPassword": "0000001B63515E7120BC166D17A66B98A717DE9B06276194E4317B5317F70EA2835B8AD262B9DD4FD6AB55", "keyPassword": "0000001B72605A837A1D1827D656F3D157F771A9B6DEC8B264626F1EFBBDA8FF65464F416F4B5C7F9FA84F",
"profile": "build_script/sign/HM4Demo.p7b", "profile": "C:\\Users\\zyz\\.ohos\\config\\default_HMDemo_i5yHT0lu8Bugf7Se0a-mWm67_DsSdIYAWNVACnIC98c=.p7b",
"signAlg": "SHA256withECDSA", "signAlg": "SHA256withECDSA",
"storeFile": "build_script/sign/HM4Demo.p12" "storeFile": "C:\\Users\\zyz\\.ohos\\config\\default_HMDemo_i5yHT0lu8Bugf7Se0a-mWm67_DsSdIYAWNVACnIC98c=.p12"
} }
} }
], ],
@@ -22,7 +22,7 @@
{ {
"name": "default", "name": "default",
"signingConfig": "default", "signingConfig": "default",
"compatibleSdkVersion": "4.0.0(10)", "compatibleSdkVersion": "5.0.0(12)",
"runtimeOS": "HarmonyOS", "runtimeOS": "HarmonyOS",
} }
], ],

View File

@@ -8,7 +8,6 @@ function textInputStyle() {
.padding(5) .padding(5)
} }
@Preview
@Component @Component
export struct PhoneInput { export struct PhoneInput {
@Prop countryCode: string = "+86" @Prop countryCode: string = "+86"

View File

@@ -15,11 +15,10 @@ export enum TitleBarMenuType{
Text = 2 Text = 2
} }
@Preview
@Component @Component
export struct TitleBar { export struct TitleBar {
@Prop title: ResourceStr; @Prop title: ResourceStr = '';
@Prop barHeight: number = 48; @Prop barHeight: number = 48;
@Prop menuPadding: number = 8; @Prop menuPadding: number = 8;

View File

@@ -0,0 +1,26 @@
import { util } from '@kit.ArkTS';
export class Res {
static getRawFileContent(name: string): string {
let content = getContext().resourceManager.getRawFileContentSync(name);
let textDecoderOptions: util.TextDecoderOptions = {
fatal: false,
ignoreBOM : true
}
let decodeWithStreamOptions: util.DecodeWithStreamOptions = {
stream: true
}
let textDecoder = util.TextDecoder.create('utf-8', textDecoderOptions);
let retStr = textDecoder.decodeWithStream( content , decodeWithStreamOptions);
return retStr;
}
static getResStr(descName: string, ...rest: string[]): ResourceStr {
try {
return $r(`app.string.${descName}`, ...rest);
} catch (e) {
return '';
}
}
}

View File

@@ -1,5 +0,0 @@
import localUnitTest from './LocalUnit.test';
export default function testsuite() {
localUnitTest();
}

View File

@@ -1,33 +0,0 @@
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
export default function localUnitTest() {
describe('localUnitTest',() => {
// Defines a test suite. Two parameters are supported: test suite name and test suite function.
beforeAll(() => {
// Presets an action, which is performed only once before all test cases of the test suite start.
// This API supports only one parameter: preset action function.
});
beforeEach(() => {
// Presets an action, which is performed before each unit test case starts.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: preset action function.
});
afterEach(() => {
// Presets a clear action, which is performed after each unit test case ends.
// The number of execution times is the same as the number of test cases defined by **it**.
// This API supports only one parameter: clear action function.
});
afterAll(() => {
// Presets a clear action, which is performed after all test cases of the test suite end.
// This API supports only one parameter: clear action function.
});
it('assertContain', 0, () => {
// Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function.
let a = 'abc';
let b = 'b';
// Defines a variety of assertion methods, which are used to declare expected boolean conditions.
expect(a).assertContain(b);
expect(a).assertEqual(a);
});
});
}

View File

@@ -2,27 +2,27 @@
chcp 65001 > nul chcp 65001 > nul
set "native_path=C:\Program Files\Huawei\DevEco Studio5\sdk\HarmonyOS-NEXT-DB1\openharmony\native\" set "native_path=C:\Program Files\Huawei\DevEco Studio5\sdk\HarmonyOS-NEXT-DB1\openharmony\native\"
::IF NOT "%~1" == "" ( :: IF NOT "%~2" == "" (
:: set "native_path=%~1" :: set "native_path=%~2"
::) :: )
echo %native_path% echo native_path: "%native_path%"
set "toolchain=%native_path%build\cmake\ohos.toolchain.cmake" set "toolchain=%native_path%build\cmake\ohos.toolchain.cmake"
echo %toolchain% echo toolchain: "%toolchain%"
set "cmake_root=%native_path%build-tools\cmake\" set "cmake_root=%native_path%build-tools\cmake\"
echo %cmake_root% echo cmake_root: "%cmake_root%"
set "cmake_path=%cmake_root%bin\cmake.exe" set "cmake_path=%cmake_root%bin\cmake.exe"
echo %cmake_path% echo cmake_path: "%cmake_path%"
set "ninja_path=%cmake_root%bin\ninja.exe" set "ninja_path=%cmake_root%bin\ninja.exe"
echo %ninja_path% echo ninja_path: "%ninja_path%"
set "make_path=C:\MinGW\msys\1.0\bin\make.exe" set "make_path=C:\MinGW\msys\1.0\bin\make.exe"
echo %make_path% echo make_path: %make_path%
set "arch=arm64-v8a" set "arch=arm64-v8a"
IF NOT "%~1" == "" ( IF NOT "%~1" == "" (
set "arch=%~1" set "arch=%~1"
) )
echo %arch% echo arch: "%arch%"
if exist build ( if exist build (
del /q /s build del /q /s build

View File

@@ -1,5 +0,0 @@
@echo off
chcp 65001 > nul
build.bat
build.bat x86_64

1
cppLib/build_x86.bat Normal file
View File

@@ -0,0 +1 @@
build.bat "x86_64"