鸿蒙应用示例:API功能集成示例及注意事项

【demo源码】:https://gitcode.com/zhongcongxu01/harmony_demo/overview

这个示例应用展示了如何集成以下功能:

  1. 获取设备的AAID(应用唯一标识符)。
  2. 启动短信应用并预填联系人信息。
  3. 启动浏览器并加载指定网页。
  4. 启动应用市场中的应用详情页面。
  5. 启动设备的设置界面(如WLAN设置、输入法设置等)。
  6. 拨打电话。
  7. 启动扫码界面。
  8. 检测指定应用是否已安装。
  9. 获取当前应用的信息。
  10. 获取设备的基本信息。
  11. 开启或关闭窗口隐私模式(防截屏录屏)。
  12. 监听网络连接状态。
  13. 获取当前设备的网络连接属性(如IP地址)。
  14. 启动相机选择器。
  15. 从相册选择图片。
  16. 设置应用的屏幕方向(竖屏或横屏)。
  17. 检测当前应用的屏幕方向。
  18. 获取当前设备类型。

【注意事项】

1、设备唯一标识 AAID(应用匿名标识符)

• 实测结果:当用户主动卸载应用后重新安装时,AAID值会发生变化。
• 建议:如果希望卸载应用后仍保持唯一标识符不变,可以考虑使用第三方库如harmony-utils来实现这一功能。

2、开启或关闭窗口隐私模式(防截屏录屏)

• 防截屏效果:当用户尝试截屏时,会有提示“当前页面涉及隐私内容,不允许截屏”。
• 防录屏效果:当设置防截屏录屏后,录屏时涉及到设置防录屏的页面将显示为黑屏,从而达到防录屏的效果。

3、判断API是否可用,使用canIUse方法的场景

在开发过程中,经常会出现以下警告:

1
The API is not supported on all devices. Use the canIUse condition to determine whether the API is supported.

  

这通常出现在某些API文档或IDE的提示信息中,表明该API并不是所有设备都支持。此时,我们需要使用canIUse方法来动态判断当前设备是否支持该API。

具体操作步骤如下:

(1). 查看API文档:首先查看API文档,确定该API是否支持所有设备。
(2). IDE提示信息:在IDE中编写代码时,如果IDE提示“该API不是所有设备都支持”,则需要使用canIUse方法。
(3). 查找@syscap值:在API文档中查找对应的@syscap值,例如SystemCapability.Window.SessionManager。
(4). 编写条件判断:在代码中使用canIUse方法,传入找到的@syscap值来判断当前设备是否支持该API。

示例代码: 假设我们要使用call.makeCall方法拨打电话,但在某些设备上可能不支持该功能,那么我们可以这样写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
if (canIUse('SystemCapability.Telephony.Call')) {
  call.makeCall("13800000000", (err: BusinessError) => {
    if (err) {
      console.error(`makeCall fail, err->${JSON.stringify(err)}`);
    } else {
      console.log(`makeCall success`);
    }
  });
} else {
  promptAction.showToast({
    message: `当前设备不支持拨打电话功能`,
    duration: 2000,
    bottom: '500lpx'
  });
}

  

在这个例子中,SystemCapability.Telephony.Call是拨打电话功能所需的系统能力。通过canIUse方法判断当前设备是否支持该能力,从而决定是否调用call.makeCall方法。

4、核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
import { bundleManager, common, Want } from '@kit.AbilityKit';
import { BusinessError, deviceInfo } from '@kit.BasicServicesKit';
import { call } from '@kit.TelephonyKit';
import { scanBarcode, scanCore } from '@kit.ScanKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { promptAction, window } from '@kit.ArkUI';
import { connection } from '@kit.NetworkKit';
import { camera, cameraPicker } from '@kit.CameraKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { resourceManager } from '@kit.LocalizationKit';
import { AAID } from '@kit.PushKit';
 
function getMmsWant() {
  let want: Want = {
    bundleName: 'com.ohos.mms',
    abilityName: 'com.ohos.mms.MainAbility',
    parameters: {
      contactObjects: JSON.stringify([{ "contactsName": 'ZhangSan', "telephone": "16888880000" }]),
      content: "短信内容测试321",
      pageFlag: 'conversation'
    }
  };
  return want
}
 
function getBrowsableWant() {
  let want: Want = {
    action: 'ohos.want.action.viewData',
    entities: ['entity.system.browsable'],
    uri: 'https://www.huawei.com'
  };
  return want
}
 
function getAppGalleryDetailWant() {
  let bundleName = "com.amap.hmapp"
  let want: Want = {
    action: 'ohos.want.action.appdetail',
    uri: 'store://appgallery.huawei.com/app/detail?id=' + bundleName, //  bundleName为需要打开应用详情的应用的包名
  };
  return want
}
 
function getWifiEntryWant() {
  let want: Want = {
    bundleName: 'com.huawei.hmos.settings',
    abilityName: 'com.huawei.hmos.settings.MainAbility',
    uri: 'wifi_entry'  // 根据”设置”应用配置的界面信息,选择不同的uri
  };
  return want
}
 
 
function getSetInputWant() {
  let want: Want = {
    bundleName: 'com.huawei.hmos.settings',
    abilityName: 'com.huawei.hmos.settings.MainAbility',
    uri: 'set_input'  // 根据”设置”应用配置的界面信息,选择不同的uri
  };
  return want
}
 
 
function getLocationManagerSettingsWant() {
  let want: Want = {
    bundleName: 'com.huawei.hmos.settings',
    abilityName: 'com.huawei.hmos.settings.MainAbility',
    uri: 'location_manager_settings'  // 根据”设置”应用配置的界面信息,选择不同的uri
  };
  return want
}
 
function makeCall() {
  if (canIUse("SystemCapability.Applications.Contacts")) {
    call.makeCall("13800000000", (err: BusinessError) => {
      if (err) {
        console.error(`makeCall fail, err->${JSON.stringify(err)}`);
      } else {
        console.log(`makeCall success`);
      }
    });
  } else {
    promptAction.showToast({
      message: `当前设备不支持该功能`,
      duration: 2000,
      bottom: '500lpx'
    });
  }
}
 
function scanCode(context: common.UIAbilityContext) {
  if (canIUse('SystemCapability.Multimedia.Scan.ScanBarcode')) {
    if (canIUse('SystemCapability.Multimedia.Scan.Core')) {
      // 定义扫码参数options
      let options: scanBarcode.ScanOptions = {
        scanTypes: [scanCore.ScanType.ALL],
        enableMultiMode: true,
        enableAlbum: true
      };
      // 可调用getContext接口获取当前页面关联的UIAbilityContext
      scanBarcode.startScanForResult(context, options,
        (error: BusinessError, result: scanBarcode.ScanResult) => {
          if (error) {
            hilog.error(0x0001, '[Scan CPSample]',
              `Failed to get ScanResult by callback with options. Code: ${error.code}, message: ${error.message}`);
            return;
          }
          // 收到扫码结果后返回
          hilog.info(0x0001, '[Scan CPSample]',
            `Succeeded in getting ScanResult by callback with options, result is ${JSON.stringify(result)}`);
          promptAction.showToast({
            message: `扫码结果:${JSON.stringify(result)}`,
            duration: 2000,
            bottom: '500lpx'
          });
        })
      return
    }
  }
  promptAction.showToast({
    message: `当前设备不支持该功能`,
    duration: 2000,
    bottom: '500lpx'
  });
}
 
function checkApp() {
  try {
    let link: string = "amapuri://"
    let appName: string = "高德地图"
    let data = bundleManager.canOpenLink(link);
    hilog.info(0x0000, 'testTag', 'canOpenLink successfully: %{public}s', JSON.stringify(data));
    if (data) {
      promptAction.showToast({
        message: `${appName} APP 已安装`,
        duration: 2000,
        bottom: '500lpx'
      });
    } else {
      promptAction.showToast({
        message: `${appName} APP 未安装`,
        duration: 2000,
        bottom: '500lpx'
      });
    }
  } catch (err) {
    if (err['code'] == 17700056) {
      /*{
      "module": {
        "querySchemes": [
          "amapuri",
        ],*/
      promptAction.showToast({
        message: '请在src/main/module.json5配置link,参考注释 querySchemes',
        duration: 2000,
        bottom: '500lpx'
      });
    } else {
      promptAction.showToast({
        message: '未知异常',
        duration: 2000,
        bottom: '500lpx'
      });
    }
    let message = (err as BusinessError).message;
    hilog.error(0x0000, 'testTag', 'canOpenLink failed: %{public}s', message);
  }
}
 
function getAppInfo() {
  let bundleFlags =
    bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION |
    bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_METADATA;
  let bundleInfo = bundleManager.getBundleInfoForSelfSync(bundleFlags)
 
  console.info('bundleInfo', JSON.stringify(bundleInfo))
  let sheets: SheetInfo[] = []
  Object.keys(bundleInfo).forEach((key: string) => {
    sheets.push({
      title: `${key}:${JSON.stringify(bundleInfo[key])}`,
      action: () => {
      }
    })
  })
  ActionSheet.show({
    title: '当前应用信息',
    subtitle: '',
    message: '',
    autoCancel: true,
    confirm: {
      defaultFocus: true,
      value: 'Confirm button',
      action: () => {
        console.log('Get Alert Dialog handled')
      }
    },
    cancel: () => {
      console.log('actionSheet canceled')
    },
    alignment: DialogAlignment.Bottom,
    offset: { dx: 0, dy: -10 },
    sheets: sheets
  })
}
 
function getDeviceInfo() {
  ActionSheet.show({
    title: '当前设备信息',
    subtitle: '',
    message: '',
    autoCancel: true,
    confirm: {
      defaultFocus: true,
      value: 'Confirm button',
      action: () => {
        console.log('Get Alert Dialog handled')
      }
    },
    cancel: () => {
      console.log('actionSheet canceled')
    },
    alignment: DialogAlignment.Bottom,
    offset: { dx: 0, dy: -10 },
    sheets: [
      {
        title: '设备品牌名称:' + deviceInfo.brand,
        action: () => {
        }
      },
      {
        title: '产品版本:' + deviceInfo.displayVersion,
        action: () => {
        }
      },
      {
        title: '系统版本:' + deviceInfo.osFullName,
        action: () => {
        }
      },
      {
        title: '系统软件API版本:' + deviceInfo.sdkApiVersion,
        action: () => {
        }
      },
      {
        title: '首个版本系统软件API版本:' + deviceInfo.firstApiVersion,
        action: () => {
        }
      },
      {
        title: '构建时间:' + deviceInfo.buildTime,
        action: () => {
        }
      },
      {
        title: '发行版系统api版本:' + deviceInfo.distributionOSApiVersion,
        action: () => {
        }
      },
    ]
  })
}
 
async function setWindowPrivacyModeTrue(context: common.UIAbilityContext) {
  let windowClass: window.Window = await window.getLastWindow(context)
  try {
    windowClass.setWindowPrivacyMode(true, (err: BusinessError) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(err));
        if (errCode == 201) {
          /*
          {
            "module": {
              "requestPermissions": [
                {
                  "name": "ohos.permission.INTERNET"
                }
              ],*/
          promptAction.showToast({
            message: `请在src/main/module.json5添加权限 "name": "ohos.permission.PRIVACY_WINDOW"`,
            duration: 2000,
            bottom: '500lpx'
          });
        }
        return;
      }
      promptAction.showToast({
        message: `已开启 防截屏录屏`,
        duration: 2000,
        bottom: '500lpx'
      });
      console.info('Succeeded in setting the window to privacy mode.');
    });
  } catch (exception) {
    console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(exception));
  }
}
 
async function setWindowPrivacyModeFalse(context: common.UIAbilityContext) {
  let windowClass: window.Window = await window.getLastWindow(context)
  try {
    windowClass.setWindowPrivacyMode(false, (err: BusinessError) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(err));
        if (errCode == 201) {
 
          promptAction.showToast({
            message: `请在src/main/module.json5添加权限 "name": "ohos.permission.PRIVACY_WINDOW"`,
            duration: 2000,
            bottom: '500lpx'
          });
        }
        return;
      }
      promptAction.showToast({
        message: `已关闭 防截屏录屏`,
        duration: 2000,
        bottom: '500lpx'
      });
      console.info('Succeeded in setting the window to privacy mode.');
    });
  } catch (exception) {
    console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(exception));
  }
}
 
function netConnectionListener() {
  let netCon: connection.NetConnection = connection.createNetConnection();
  // 先使用register接口注册订阅事件
  netCon.register((error: BusinessError) => {
    console.log(JSON.stringify(error));
    if (error) {
      if (error.code == 201) {
        promptAction.showToast({
          message: `请在src/main/module.json5添加权限 "name": "ohos.permission.GET_NETWORK_INFO"`,
          duration: 2000,
          bottom: '500lpx'
        });
      } else {
        promptAction.showToast({
          message: `${JSON.stringify(error)}`,
          duration: 2000,
          bottom: '500lpx'
        });
      }
      return;
    }
    promptAction.showToast({
      message: `已开启 网络状态监听`,
      duration: 2000,
      bottom: '500lpx'
    });
  });
  // 订阅网络丢失事件。调用register后,才能接收到此事件通知
  netCon.on('netLost', (data: connection.NetHandle) => {
    console.info("Succeeded to get data: netLost " + JSON.stringify(data));
    promptAction.showToast({
      message: `已关闭 网络`,
      duration: 2000,
      bottom: '500lpx'
    });
  });
  // 订阅网络能力变化事件。调用register后,才能接收到此事件通知
  netCon.on('netConnectionPropertiesChange', (data: connection.NetConnectionPropertyInfo) => {
    console.info("Succeeded to get data: netConnectionPropertiesChange " + JSON.stringify(data));
    promptAction.showToast({
      message: `已开启 网络`,
      duration: 2000,
      bottom: '500lpx'
    });
  });
}
 
async function startCameraPicker(context: common.UIAbilityContext) {
  try {
    let pickerProfile: cameraPicker.PickerProfile = {
      cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK
    };
    let pickerResult: cameraPicker.PickerResult = await cameraPicker.pick(context,
      [cameraPicker.PickerMediaType.PHOTO, cameraPicker.PickerMediaType.VIDEO], pickerProfile);
    console.log("the pick pickerResult is:" + JSON.stringify(pickerResult)); //拍照结果
    if (pickerResult.resultCode == 0) {
      context.eventHub.emit("updateImage", pickerResult.resultUri)
    }
  } catch (error) {
    let err = error as BusinessError;
    console.error(`the pick call failed. error code: ${err.code}`);
  }
}
 
function selectPhoto(context: common.UIAbilityContext) {
  try {
    let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
    PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
    PhotoSelectOptions.maxSelectNumber = 1;
    let photoPicker = new photoAccessHelper.PhotoViewPicker();
    photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: photoAccessHelper.PhotoSelectResult) => {
      console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult));
      if (PhotoSelectResult.photoUris?.[0]) {
        context.eventHub.emit("updateImage", PhotoSelectResult.photoUris?.[0])
      }
    }).catch((err: BusinessError) => {
      console.error(`PhotoViewPicker.select failed with err: ${err.code}, ${err.message}`);
    });
  } catch (error) {
    let err: BusinessError = error as BusinessError;
    console.error(`PhotoViewPicker failed with err: ${err.code}, ${err.message}`);
  }
}
 
function setAppLandscapeOrientation() {
  window.getLastWindow(getContext()).then((windowClass) => {
    windowClass.setPreferredOrientation(window.Orientation.PORTRAIT)
  })
}
 
function setAppPortraitOrientation() {
  window.getLastWindow(getContext()).then((windowClass) => {
    windowClass.setPreferredOrientation(window.Orientation.LANDSCAPE)
  })
}
 
function detectAppOrientation() {
  promptAction.showToast({
    message: getContext().resourceManager.getConfigurationSync().direction ===
    resourceManager.Direction.DIRECTION_VERTICAL ?
      "竖屏" : "横屏"
  })
}
 
function getDeviceType() {
  let getDeviceTypeInfo = () => {
    let
      deviceType = getContext().resourceManager.getDeviceCapabilitySync().deviceType;
    switch (deviceType) {
      case resourceManager.DeviceType.DEVICE_TYPE_PHONE:
        return "手机";
      case resourceManager.DeviceType.DEVICE_TYPE_TABLET:
        return "平板";
      case resourceManager.DeviceType.DEVICE_TYPE_PC:
        return "电脑";
      case resourceManager.DeviceType.DEVICE_TYPE_TV:
        return "电视";
      case resourceManager.DeviceType.DEVICE_TYPE_CAR:
        return "汽车";
      case resourceManager.DeviceType.DEVICE_TYPE_WEARABLE:
        return "穿戴";
      case resourceManager.DeviceType.DEVICE_TYPE_2IN1:
        return "2IN1";
      default:
        return "未知"
    }
  }
  promptAction.showToast({
    message: getDeviceTypeInfo()
  })
}
 
function getDefaultNet() {
  let isDefaultNet = connection.hasDefaultNetSync();
  promptAction.showToast({
    message: `当前${isDefaultNet ? '有网络' : '无网络'}`
  })
}
 
function getConnectionProperties() {
  connection.getDefaultNet().then((netHandle: connection.NetHandle) => {
    connection.getConnectionProperties(netHandle, (error: BusinessError, data: connection.ConnectionProperties) => {
      if (error) {
        console.error(`Failed to get connection properties. Code:${error.code}, message:${error.message}`);
        return;
      }
      console.info("Succeeded to get data: " + JSON.stringify(data));
      try {
        let ip = data['linkAddresses'][0]['address']['address']
        console.info('本地ip:', ip)
        promptAction.showToast({
          message: `当前ip:${ip}`
        })
      } catch (e) {
        console.error("e", JSON.stringify(e));
 
      }
 
    })
  });
 
}
 
function getAAID() {
  AAID.getAAID().then((data: string) => {
    ActionSheet.show({
      title: '当前AAID',
      subtitle: `${data}`,
      message: `实测当用户主动卸载APP后重新安装时,AAID值会改变。`,
      autoCancel: true,
      confirm: {
        defaultFocus: true,
        value: 'Confirm button',
        action: () => {
          console.log('Get Alert Dialog handled')
        }
      },
      cancel: () => {
        console.log('actionSheet canceled')
      },
      alignment: DialogAlignment.Bottom,
      offset: { dx: 0, dy: -10 },
      sheets: [
        {
          title: '如果希望卸载APP后依旧不变,建议使用第三方harmony-utils',
          action: () => {
          }
        }
      ]
    })
    hilog.info(0x0000, 'testTag', 'Get AAID successfully: %{public}s', data);
  }).catch((err: BusinessError) => {
    hilog.error(0x0000, 'testTag', 'Get AAID failed: %{public}d %{public}s', err.code, err.message);
  });
}
 
class Item {
  key: string
  want: Want | Function
 
  constructor(key: string, want: Want | Function) {
    this.key = key
    this.want = want
  }
}
 
//拉起功能示例
@Entry
@Component
struct Index {
  @State array: Item[] = []
  @State imageUrl: string | undefined = undefined
 
  aboutToAppear(): void {
 
    getContext(this).eventHub.on('updateImage', (data: string) => {
      this.imageUrl = data
      console.info('imageUrl', this.imageUrl)
    })
 
    this.array.push(new Item('获取设备的AAID', getAAID))
    this.array.push(new Item('拉起短信界面并指定联系人', getMmsWant()))
    this.array.push(new Item('拉起浏览器并打开指定网页', getBrowsableWant()))
    this.array.push(new Item('拉起应用市场对应的应用详情界面', getAppGalleryDetailWant()))
    this.array.push(new Item('拉起设置应用HOME-WLAN界面', getWifiEntryWant()))
    this.array.push(new Item('拉起HOME-系统和更新-输入法页面', getSetInputWant()))
    this.array.push(new Item('拉起开启定位的设置页', getLocationManagerSettingsWant()))
    this.array.push(new Item('拉起拨号界面并显示待拨出的号码', makeCall))
    this.array.push(new Item('拉起扫码页面', scanCode))
    this.array.push(new Item('判断是否安装了某个APP', checkApp))
    this.array.push(new Item('获取应用信息', getAppInfo))
    this.array.push(new Item('获取设备信息', getDeviceInfo))
    this.array.push(new Item('开启防截屏录屏', setWindowPrivacyModeTrue))
    this.array.push(new Item('关闭防截屏录屏', setWindowPrivacyModeFalse))
    this.array.push(new Item('开启网络状态监听', netConnectionListener))
    this.array.push(new Item('判断当前网络链接状态', getDefaultNet))
    this.array.push(new Item('获取手机当前连接wifi的本机ip', getConnectionProperties))
    this.array.push(new Item('拉起相机', startCameraPicker))
    this.array.push(new Item('拉起相册', selectPhoto))
    this.array.push(new Item('设置当前app以竖屏方式显示', setAppLandscapeOrientation))
    this.array.push(new Item('设置当前app以横屏方式显示', setAppPortraitOrientation))
    this.array.push(new Item('判断APP是横屏还是竖屏', detectAppOrientation))
    this.array.push(new Item('获取当前设备类型', getDeviceType))
 
 
  }
 
  build() {
    Stack() {
      Scroll() {
        Column({ space: 5 }) {
          ForEach(this.array, (item: Item, index: number) => {
            Button(`【${index + 1}】${item.key}`).onClick(() => {
              if (item.want instanceof Function) {
                item.want(getContext(this))
              } else {
                const context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
                context.startAbility(item.want).then(() => {
                  console.info('Start successfully.');
                }).catch((err: BusinessError) => {
                  console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`);
                });
              }
            })
          })
        }
      }
      .align(Alignment.Top)
      .width('100%')
      .height('100%')
 
      if (this.imageUrl) {
        Stack() {
          Image(this.imageUrl)
            .width('300lpx')
            .height('300lpx')
            .borderRadius(30)
        }.width('100%').height('100%').backgroundColor("#80000000").onClick(() => {
          this.imageUrl = undefined
        })
      }
    }.width('100%').height('100%')
  }
}

  

 

posted @   zhongcx  阅读(110)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示