【HarmonyOS开发案例】项目通用功能-demo

159 篇文章 0 订阅
159 篇文章 0 订阅

补充:控制屏幕方向、判断屏幕方向、获取设备类型。用于提前判断类型,提前加载不同布局。

image.png

import { promptAction, window } from '@kit.ArkUI'
import { resourceManager } from '@kit.LocalizationKit'

@Entry
@Component
struct Page41 {
  build() {
    Column({ space: 5 }) {
      Button('设置当前app以横屏方式显示').onClick(() => {
        window.getLastWindow(getContext()).then((windowClass) => {
          windowClass.setPreferredOrientation(window.Orientation.PORTRAIT)
        })
      })
      Button('设置当前app以竖屏方式显示').onClick(() => {
        window.getLastWindow(getContext()).then((windowClass) => {
          windowClass.setPreferredOrientation(window.Orientation.LANDSCAPE)
        })
      })
      Button('判断APP是横屏还是竖屏').onClick(() => {
        promptAction.showToast({
          message: getContext().resourceManager.getConfigurationSync().direction ===
          resourceManager.Direction.DIRECTION_VERTICAL ?
            "竖屏" : "横屏"
        })
      })
      Button('获取当前设备类型').onClick(() => {
        promptAction.showToast({
          message: this.getDeviceTypeInfo()
        })
      })
    }
    .height('100%')
    .width('100%')
  }

  getDeviceTypeInfo(): string {
    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 "未知"
    }
  }
}

===================================

【效果】真机 API 12,DevEco Studio 5.0.3.403

cke_412.png

获取设备唯一标识需要
ohpm i @pura/harmony-utils

src/main/ets/pages/Index.ets

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 { DeviceUtil } from '@pura/harmony-utils'

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() {
  call.makeCall("13800000000", (err: BusinessError) => {
    if (err) {
      console.error(`makeCall fail, err->${JSON.stringify(err)}`);
    } else {
      console.log(`makeCall success`);
    }
  });
}

function scanCode(context: common.UIAbilityContext) {
  // 定义扫码参数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'
      });
    })
}

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'
    });
  });
}

function getDeviceId() {
  DeviceUtil.getDeviceId().then((data:string)=>{
    ActionSheet.show({
      title: '当前设备唯一ID如下',
      subtitle: `${data}`,
      message: `工具开源地址:https://ohpm.openharmony.cn/#/cn/detail/@pura%2Fharmony-utils`,
      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后依旧不变',
          action: () => {
          }
        },
        {
          title: '需要:ohpm i @pura/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);
  });

}

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 example01(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}`);
  }
}

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('拉起短信界面并指定联系人', 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('获取设备唯一标识', getDeviceId))
    this.array.push(new Item('拉起相机', startCameraPicker))
    this.array.push(new Item('拉起相册', example01))

  }

  build() {
    Stack() {
      Scroll() {
        Column({ space: 5 }) {
          ForEach(this.array, (item: Item, index: number) => {
            Button(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%')
  }
}

src/main/module.json5

{
  "module": {
    "requestPermissions": [
      {
        "name": "ohos.permission.PRIVACY_WINDOW"
      },
      {
        "name": "ohos.permission.GET_NETWORK_INFO"
      }
    ],
    "querySchemes": [
      "amapuri",
    ],

最后

小编在之前的鸿蒙系统扫盲中,有很多朋友给我留言,不同的角度的问了一些问题,我明显感觉到一点,那就是许多人参与鸿蒙开发,但是又不知道从哪里下手,因为资料太多,太杂,教授的人也多,无从选择。有很多小伙伴不知道学习哪些鸿蒙开发技术?不知道需要重点掌握哪些鸿蒙应用开发知识点?而且学习时频繁踩坑,最终浪费大量时间。所以有一份实用的鸿蒙(HarmonyOS NEXT)资料用来跟着学习是非常有必要的。 

为了确保高效学习,建议规划清晰的学习路线,涵盖以下关键阶段:

 →【纯血版鸿蒙全套最新学习资料】希望这一份鸿蒙学习资料能够给大家带来帮助~


 鸿蒙(HarmonyOS NEXT)最新学习路线

该路线图包含基础技能、就业必备技能、多媒体技术、六大电商APP、进阶高级技能、实战就业级设备开发,不仅补充了华为官网未涉及的解决方案

路线图适合人群:

IT开发人员:想要拓展职业边界
零基础小白:鸿蒙爱好者,希望从0到1学习,增加一项技能。
技术提升/进阶跳槽:发展瓶颈期,提升职场竞争力,快速掌握鸿蒙技术

2.视频学习资料+学习PDF文档

HarmonyOS Next 最新全套视频教程 (鸿蒙语法ArkTS、TypeScript、ArkUI教程……)

​​

 纯血版鸿蒙全套学习资料(面试、文档、全套视频等)

                   

​​​​鸿蒙APP开发必备

​​

总结

【纯血版鸿蒙全套最新学习资料】

总的来说,华为鸿蒙不再兼容安卓,对程序员来说是一个挑战,也是一个机会。只有积极应对变化,不断学习和提升自己,才能在这个变革的时代中立于不败之地。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值