OpenHarmony开发实例:【仿桌面应用】

news2024/11/25 16:29:26

 介绍

本示例实现了一个简单桌面应用,实现了以下几点功能:

1.展示了系统安装的应用,实现点击启动、应用上滑弹出卡片、卡片添加到桌面、卡片移除功能。

2.实现桌面数据持久化存储,应用支持卸载、监听应用卸载和安装并显示。

3.实现最近任务管理功能,包括任务卡片加锁、解锁、清理和清理所有任务功能。

4.通过点击应用图标或点击由长按图标弹出的菜单栏中的打开按钮的方式打开应用,是以打开最近任务方式拉起应用Ability。

效果预览

image.png

使用说明

1.安装编译的hap包,使用hdc shell aa start -b ohos.samples.launcher -a MainAbility命令启动应用,应用启动后显示系统安装的应用。

2.点击应用主界面上的应用图标可以启动应用,长按弹出菜单,点击打开可以正常启动应用。

3.图库等支持卡片的应用,长按菜单中有服务卡片,点击进入卡片预览界面,在卡片预览界面点击添加到桌面,返回到桌面并且卡片成功添加到桌面。

4.上滑图库等支持卡片的应用,可以弹出默认上滑卡片,点击上滑卡片右上角的**+**图标,可以添加卡片到桌面。

5.应用在桌面界面,使用hdc install安装一个应用,桌面可以监听到应用安装,并显示新安装的应用到桌面上。

6.应用在桌面界面,使用hdc uninstall 卸载第5步安装的应用,桌面可以监听到卸载,并移除桌面上的应用。

7.在桌面空白处上滑,可以进入最近任务管理界面,下滑任务卡片可以加锁/解锁,上滑卡片可以清理该后台任务,点击垃圾桶可以清除所有后台任务(加锁的应用不会被清理掉)。

代码解读

鸿蒙next开发文档参考了:qr23.cn/AKFP8k点击或者复制转到。

entry/src/main/ets/
|---Application
|   |---MyAbilityStage.ts
|---components
|   |---FormManagerComponent.ets               // 弹窗组件
|---MainAbility
|   |---MainAbility.ts
|---manager
|   |---WindowManager.ts                       // 数据类型
|---pages
|   |---FormPage.ets                           // 首页
|   |---Home.ets                               // 详情页面
|   |---RecentsPage.ets                        // 详情页面

具体实现

搜狗高速浏览器截图20240326151344.png

  • 获取应用功能模块

    • 使用launcherBundleManager模块接口(系统能力:SystemCapability.BundleManager.BundleFramework),获取所有应用信息和给定包名获取应用信息,实现桌面展示所有安装的应用。使用on接口监听应用的安装和卸载从而实现应用安装和卸载刷新桌面。
  • 源码链接:[LauncherAbilityManager.ts]

/*

 * Copyright (c) 2022-2023 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */



import installer from '@ohos.bundle.installer';

import launcherBundleManager from '@ohos.bundle.launcherBundleManager';

import bundleMonitor from '@ohos.bundle.bundleMonitor';

import osAccount from '@ohos.account.osAccount'

import { AppItemInfo } from '../bean/AppItemInfo'

import { CheckEmptyUtils } from '../utils/CheckEmptyUtils'

import { CommonConstants } from '../constants/CommonConstants'

import { EventConstants } from '../constants/EventConstants'

import { ResourceManager } from './ResourceManager'

import { Logger } from '../utils/Logger'

import type { BusinessError } from '@ohos.base';



const TAG: string = 'LauncherAbilityManager'



/**

 * Wrapper class for innerBundleManager and formManager interfaces.

 */

export class LauncherAbilityManager {

  private static readonly BUNDLE_STATUS_CHANGE_KEY_REMOVE = 'remove'

  private static readonly BUNDLE_STATUS_CHANGE_KEY_ADD = 'add'

  private static launcherAbilityManager: LauncherAbilityManager = undefined

  private readonly mAppMap = new Map<string, AppItemInfo>()

  private mResourceManager: ResourceManager = undefined

  private readonly mLauncherAbilityChangeListeners: any[] = []

  private mUserId: number = 100

  private context: any = undefined



  constructor(context) {

    this.context = context

    this.mResourceManager = ResourceManager.getInstance(context)

    const osAccountManager = osAccount.getAccountManager()

    osAccountManager.getOsAccountLocalIdFromProcess((err, localId) => {

      Logger.debug(TAG, `getOsAccountLocalIdFromProcess localId ${localId}`)

      this.mUserId = localId

    })

  }



  /**

   * Get the application data model object.

   *

   * @return {object} application data model singleton

   */

  static getInstance(context): LauncherAbilityManager {

    if (this.launcherAbilityManager === null || this.launcherAbilityManager === undefined) {

      this.launcherAbilityManager = new LauncherAbilityManager(context)

    }

    return this.launcherAbilityManager

  }



  /**

   * get all app List info from BMS

   *

   * @return 应用的入口Ability信息列表

   */

  async getLauncherAbilityList(): Promise<AppItemInfo[]> {

    Logger.info(TAG, 'getLauncherAbilityList begin')

    let abilityList = await launcherBundleManager.getAllLauncherAbilityInfo(this.mUserId)

    const appItemInfoList = new Array<AppItemInfo>()

    if (CheckEmptyUtils.isEmpty(abilityList)) {

      Logger.info(TAG, 'getLauncherAbilityList Empty')

      return appItemInfoList

    }

    for (let i = 0; i < abilityList.length; i++) {

      let appItem = await this.transToAppItemInfo(abilityList[i])

      appItemInfoList.push(appItem)

    }

    return appItemInfoList

  }



  /**

   * get AppItemInfo from BMS with bundleName

   * @params bundleName

   * @return AppItemInfo

   */

  async getAppInfoByBundleName(bundleName: string): Promise<AppItemInfo | undefined> {

    let appItemInfo: AppItemInfo | undefined = undefined

    // get from cache

    if (this.mAppMap != null && this.mAppMap.has(bundleName)) {

      appItemInfo = this.mAppMap.get(bundleName)

    }

    if (appItemInfo != undefined) {

      Logger.info(TAG, `getAppInfoByBundleName from cache: ${JSON.stringify(appItemInfo)}`)

      return appItemInfo

    }

    // get from system

    let abilityInfos = await launcherBundleManager.getLauncherAbilityInfo(bundleName, this.mUserId)

    if (abilityInfos == undefined || abilityInfos.length == 0) {

      Logger.info(TAG, `${bundleName} has no launcher ability`)

      return undefined

    }

    let appInfo = abilityInfos[0]

    const data = await this.transToAppItemInfo(appInfo)

    Logger.info(TAG, `getAppInfoByBundleName from BMS: ${JSON.stringify(data)}`)

    return data

  }



  private async transToAppItemInfo(info): Promise<AppItemInfo> {

    const appItemInfo = new AppItemInfo()

    appItemInfo.appName = await this.mResourceManager.getAppNameSync(

    info.labelId, info.elementName.bundleName, info.applicationInfo.label

    )

    appItemInfo.isSystemApp = info.applicationInfo.systemApp

    appItemInfo.isUninstallAble = info.applicationInfo.removable

    appItemInfo.appIconId = info.iconId

    appItemInfo.appLabelId = info.labelId

    appItemInfo.bundleName = info.elementName.bundleName

    appItemInfo.abilityName = info.elementName.abilityName

    await this.mResourceManager.updateIconCache(appItemInfo.appIconId, appItemInfo.bundleName)

    this.mAppMap.set(appItemInfo.bundleName, appItemInfo)

    return appItemInfo

  }





  /**

   * 启动应用

   *

   * @params paramAbilityName Ability名

   * @params paramBundleName 应用包名

   */

  startLauncherAbility(paramAbilityName, paramBundleName) {

    Logger.info(TAG, `startApplication abilityName: ${paramAbilityName}, bundleName: ${paramBundleName}`)

    this.context.startAbility({

      bundleName: paramBundleName,

      abilityName: paramAbilityName

    }).then(() => {

      Logger.info(TAG, 'startApplication promise success')

    }, (err) => {

      Logger.error(TAG, `startApplication promise error: ${JSON.stringify(err)}`)

    })

  }



  /**

   * 通过桌面图标启动应用

   *

   * @params paramAbilityName Ability名

   * @params paramBundleName 应用包名

   */

  startLauncherAbilityFromRecent(paramAbilityName, paramBundleName): void {

    Logger.info(TAG, `startApplication abilityName: ${paramAbilityName}, bundleName: ${paramBundleName}`);

    this.context.startRecentAbility({

      bundleName: paramBundleName,

      abilityName: paramAbilityName

    }).then(() => {

      Logger.info(TAG, 'startApplication promise success');

    }, (err) => {

      Logger.error(TAG, `startApplication promise error: ${JSON.stringify(err)}`);

    });

  }



  /**

   * 卸载应用

   *

   * @params bundleName 应用包名

   * @params callback 卸载回调

   */

  async uninstallLauncherAbility(bundleName: string, callback): Promise<void> {

    Logger.info(TAG, `uninstallLauncherAbility bundleName: ${bundleName}`);

    const bundlerInstaller = await installer.getBundleInstaller();

    bundlerInstaller.uninstall(bundleName, {

      userId: this.mUserId,

      installFlag: 0,

      isKeepData: false

    }, (err: BusinessError) => {

      Logger.info(TAG, `uninstallLauncherAbility result => ${JSON.stringify(err)}`);

      callback(err);

    })

  }



  /**

   * 开始监听系统应用状态.

   *

   * @params listener 监听对象

   */

  registerLauncherAbilityChangeListener(listener: any): void {

    if (!CheckEmptyUtils.isEmpty(listener)) {

      if (this.mLauncherAbilityChangeListeners.length == 0) {

        bundleMonitor.on(LauncherAbilityManager.BUNDLE_STATUS_CHANGE_KEY_ADD, (bundleChangeInfo) => {

          Logger.debug(TAG, `mBundleStatusCallback add bundleName: ${bundleChangeInfo.bundleName},

            userId: ${bundleChangeInfo.userId}, mUserId ${this.mUserId}`)

          if (this.mUserId === bundleChangeInfo.userId) {

            this.notifyLauncherAbilityChange(EventConstants.EVENT_PACKAGE_ADDED,

              bundleChangeInfo.bundleName, bundleChangeInfo.userId)

          }

        })

        bundleMonitor.on(LauncherAbilityManager.BUNDLE_STATUS_CHANGE_KEY_REMOVE, (bundleChangeInfo) => {

          Logger.debug(TAG, `mBundleStatusCallback remove bundleName: ${bundleChangeInfo.bundleName},

            userId: ${bundleChangeInfo.userId}, mUserId ${this.mUserId}`)

          if (this.mUserId === bundleChangeInfo.userId) {

            this.notifyLauncherAbilityChange(EventConstants.EVENT_PACKAGE_REMOVED,

              bundleChangeInfo.bundleName, bundleChangeInfo.userId)

          }

          AppStorage.Set('isRefresh', true)

        })

      }

      const index = this.mLauncherAbilityChangeListeners.indexOf(listener)

      if (index == CommonConstants.INVALID_VALUE) {

        this.mLauncherAbilityChangeListeners.push(listener)

      }

    }

  }



  /**

   * 取消监听系统应用状态.

   *

   * @params listener 监听对象

   */

  unregisterLauncherAbilityChangeListener(listener: any): void {

    if (!CheckEmptyUtils.isEmpty(listener)) {

      const index = this.mLauncherAbilityChangeListeners.indexOf(listener)

      if (index != CommonConstants.INVALID_VALUE) {

        this.mLauncherAbilityChangeListeners.splice(index, 1)

      }

      if (this.mLauncherAbilityChangeListeners.length == 0) {

        bundleMonitor.off(LauncherAbilityManager.BUNDLE_STATUS_CHANGE_KEY_ADD)

        bundleMonitor.off(LauncherAbilityManager.BUNDLE_STATUS_CHANGE_KEY_REMOVE)

      }

    }

  }



  private notifyLauncherAbilityChange(event: string, bundleName: string, userId: number): void {

    for (let index = 0; index < this.mLauncherAbilityChangeListeners.length; index++) {

      this.mLauncherAbilityChangeListeners[index](event, bundleName, userId)

    }

  }

}
  • 接口参考:[@ohos.bundle.launcherBundleManager]

  • 应用卸载功能模块

  • 使用bundle模块的getBundleInstaller接口获取到BundleInstaller(系统能力:SystemCapability.BundleManager.BundleFramework),调用uninstall接口实现应用卸载功能。

  • 源码链接:[LauncherAbilityManager.ts]

/*

 * Copyright (c) 2022-2023 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */



import installer from '@ohos.bundle.installer';

import launcherBundleManager from '@ohos.bundle.launcherBundleManager';

import bundleMonitor from '@ohos.bundle.bundleMonitor';

import osAccount from '@ohos.account.osAccount'

import { AppItemInfo } from '../bean/AppItemInfo'

import { CheckEmptyUtils } from '../utils/CheckEmptyUtils'

import { CommonConstants } from '../constants/CommonConstants'

import { EventConstants } from '../constants/EventConstants'

import { ResourceManager } from './ResourceManager'

import { Logger } from '../utils/Logger'

import type { BusinessError } from '@ohos.base';



const TAG: string = 'LauncherAbilityManager'



/**

 * Wrapper class for innerBundleManager and formManager interfaces.

 */

export class LauncherAbilityManager {

  private static readonly BUNDLE_STATUS_CHANGE_KEY_REMOVE = 'remove'

  private static readonly BUNDLE_STATUS_CHANGE_KEY_ADD = 'add'

  private static launcherAbilityManager: LauncherAbilityManager = undefined

  private readonly mAppMap = new Map<string, AppItemInfo>()

  private mResourceManager: ResourceManager = undefined

  private readonly mLauncherAbilityChangeListeners: any[] = []

  private mUserId: number = 100

  private context: any = undefined



  constructor(context) {

    this.context = context

    this.mResourceManager = ResourceManager.getInstance(context)

    const osAccountManager = osAccount.getAccountManager()

    osAccountManager.getOsAccountLocalIdFromProcess((err, localId) => {

      Logger.debug(TAG, `getOsAccountLocalIdFromProcess localId ${localId}`)

      this.mUserId = localId

    })

  }



  /**

   * Get the application data model object.

   *

   * @return {object} application data model singleton

   */

  static getInstance(context): LauncherAbilityManager {

    if (this.launcherAbilityManager === null || this.launcherAbilityManager === undefined) {

      this.launcherAbilityManager = new LauncherAbilityManager(context)

    }

    return this.launcherAbilityManager

  }



  /**

   * get all app List info from BMS

   *

   * @return 应用的入口Ability信息列表

   */

  async getLauncherAbilityList(): Promise<AppItemInfo[]> {

    Logger.info(TAG, 'getLauncherAbilityList begin')

    let abilityList = await launcherBundleManager.getAllLauncherAbilityInfo(this.mUserId)

    const appItemInfoList = new Array<AppItemInfo>()

    if (CheckEmptyUtils.isEmpty(abilityList)) {

      Logger.info(TAG, 'getLauncherAbilityList Empty')

      return appItemInfoList

    }

    for (let i = 0; i < abilityList.length; i++) {

      let appItem = await this.transToAppItemInfo(abilityList[i])

      appItemInfoList.push(appItem)

    }

    return appItemInfoList

  }



  /**

   * get AppItemInfo from BMS with bundleName

   * @params bundleName

   * @return AppItemInfo

   */

  async getAppInfoByBundleName(bundleName: string): Promise<AppItemInfo | undefined> {

    let appItemInfo: AppItemInfo | undefined = undefined

    // get from cache

    if (this.mAppMap != null && this.mAppMap.has(bundleName)) {

      appItemInfo = this.mAppMap.get(bundleName)

    }

    if (appItemInfo != undefined) {

      Logger.info(TAG, `getAppInfoByBundleName from cache: ${JSON.stringify(appItemInfo)}`)

      return appItemInfo

    }

    // get from system

    let abilityInfos = await launcherBundleManager.getLauncherAbilityInfo(bundleName, this.mUserId)

    if (abilityInfos == undefined || abilityInfos.length == 0) {

      Logger.info(TAG, `${bundleName} has no launcher ability`)

      return undefined

    }

    let appInfo = abilityInfos[0]

    const data = await this.transToAppItemInfo(appInfo)

    Logger.info(TAG, `getAppInfoByBundleName from BMS: ${JSON.stringify(data)}`)

    return data

  }



  private async transToAppItemInfo(info): Promise<AppItemInfo> {

    const appItemInfo = new AppItemInfo()

    appItemInfo.appName = await this.mResourceManager.getAppNameSync(

    info.labelId, info.elementName.bundleName, info.applicationInfo.label

    )

    appItemInfo.isSystemApp = info.applicationInfo.systemApp

    appItemInfo.isUninstallAble = info.applicationInfo.removable

    appItemInfo.appIconId = info.iconId

    appItemInfo.appLabelId = info.labelId

    appItemInfo.bundleName = info.elementName.bundleName

    appItemInfo.abilityName = info.elementName.abilityName

    await this.mResourceManager.updateIconCache(appItemInfo.appIconId, appItemInfo.bundleName)

    this.mAppMap.set(appItemInfo.bundleName, appItemInfo)

    return appItemInfo

  }





  /**

   * 启动应用

   *

   * @params paramAbilityName Ability名

   * @params paramBundleName 应用包名

   */

  startLauncherAbility(paramAbilityName, paramBundleName) {

    Logger.info(TAG, `startApplication abilityName: ${paramAbilityName}, bundleName: ${paramBundleName}`)

    this.context.startAbility({

      bundleName: paramBundleName,

      abilityName: paramAbilityName

    }).then(() => {

      Logger.info(TAG, 'startApplication promise success')

    }, (err) => {

      Logger.error(TAG, `startApplication promise error: ${JSON.stringify(err)}`)

    })

  }



  /**

   * 通过桌面图标启动应用

   *

   * @params paramAbilityName Ability名

   * @params paramBundleName 应用包名

   */

  startLauncherAbilityFromRecent(paramAbilityName, paramBundleName): void {

    Logger.info(TAG, `startApplication abilityName: ${paramAbilityName}, bundleName: ${paramBundleName}`);

    this.context.startRecentAbility({

      bundleName: paramBundleName,

      abilityName: paramAbilityName

    }).then(() => {

      Logger.info(TAG, 'startApplication promise success');

    }, (err) => {

      Logger.error(TAG, `startApplication promise error: ${JSON.stringify(err)}`);

    });

  }



  /**

   * 卸载应用

   *

   * @params bundleName 应用包名

   * @params callback 卸载回调

   */

  async uninstallLauncherAbility(bundleName: string, callback): Promise<void> {

    Logger.info(TAG, `uninstallLauncherAbility bundleName: ${bundleName}`);

    const bundlerInstaller = await installer.getBundleInstaller();

    bundlerInstaller.uninstall(bundleName, {

      userId: this.mUserId,

      installFlag: 0,

      isKeepData: false

    }, (err: BusinessError) => {

      Logger.info(TAG, `uninstallLauncherAbility result => ${JSON.stringify(err)}`);

      callback(err);

    })

  }



  /**

   * 开始监听系统应用状态.

   *

   * @params listener 监听对象

   */

  registerLauncherAbilityChangeListener(listener: any): void {

    if (!CheckEmptyUtils.isEmpty(listener)) {

      if (this.mLauncherAbilityChangeListeners.length == 0) {

        bundleMonitor.on(LauncherAbilityManager.BUNDLE_STATUS_CHANGE_KEY_ADD, (bundleChangeInfo) => {

          Logger.debug(TAG, `mBundleStatusCallback add bundleName: ${bundleChangeInfo.bundleName},

            userId: ${bundleChangeInfo.userId}, mUserId ${this.mUserId}`)

          if (this.mUserId === bundleChangeInfo.userId) {

            this.notifyLauncherAbilityChange(EventConstants.EVENT_PACKAGE_ADDED,

              bundleChangeInfo.bundleName, bundleChangeInfo.userId)

          }

        })

        bundleMonitor.on(LauncherAbilityManager.BUNDLE_STATUS_CHANGE_KEY_REMOVE, (bundleChangeInfo) => {

          Logger.debug(TAG, `mBundleStatusCallback remove bundleName: ${bundleChangeInfo.bundleName},

            userId: ${bundleChangeInfo.userId}, mUserId ${this.mUserId}`)

          if (this.mUserId === bundleChangeInfo.userId) {

            this.notifyLauncherAbilityChange(EventConstants.EVENT_PACKAGE_REMOVED,

              bundleChangeInfo.bundleName, bundleChangeInfo.userId)

          }

          AppStorage.Set('isRefresh', true)

        })

      }

      const index = this.mLauncherAbilityChangeListeners.indexOf(listener)

      if (index == CommonConstants.INVALID_VALUE) {

        this.mLauncherAbilityChangeListeners.push(listener)

      }

    }

  }



  /**

   * 取消监听系统应用状态.

   *

   * @params listener 监听对象

   */

  unregisterLauncherAbilityChangeListener(listener: any): void {

    if (!CheckEmptyUtils.isEmpty(listener)) {

      const index = this.mLauncherAbilityChangeListeners.indexOf(listener)

      if (index != CommonConstants.INVALID_VALUE) {

        this.mLauncherAbilityChangeListeners.splice(index, 1)

      }

      if (this.mLauncherAbilityChangeListeners.length == 0) {

        bundleMonitor.off(LauncherAbilityManager.BUNDLE_STATUS_CHANGE_KEY_ADD)

        bundleMonitor.off(LauncherAbilityManager.BUNDLE_STATUS_CHANGE_KEY_REMOVE)

      }

    }

  }



  private notifyLauncherAbilityChange(event: string, bundleName: string, userId: number): void {

    for (let index = 0; index < this.mLauncherAbilityChangeListeners.length; index++) {

      this.mLauncherAbilityChangeListeners[index](event, bundleName, userId)

    }

  }

}

  • 接口参考:[@ohos.bundle]

  • 添加卡片功能模块

  • 使用formHost接口(系统能力:SystemCapability.Ability.Form),获取应用卡片信息,使用FormComponent组件展示卡片内容,从而实现添加卡片到桌面的功能。

  • 源码链接:[FormManager.ts]

/*

 * Copyright (c) 2022 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */



import formManagerAbility from '@ohos.app.form.formHost'

import { CardItemInfo } from '../bean/CardItemInfo'

import { CommonConstants } from '../constants/CommonConstants'

import { Logger } from '../utils/Logger'



const TAG: string = 'FormManager'



/**

 * Wrapper class for formManager interfaces.

 */

class FormManagerModel {

  private readonly CARD_SIZE_1x2: number[] = [1, 2]

  private readonly CARD_SIZE_2x2: number[] = [2, 2]

  private readonly CARD_SIZE_2x4: number[] = [2, 4]

  private readonly CARD_SIZE_4x4: number[] = [4, 4]



  /**

   * get all form info

   *

   * @return Array<CardItemInfo> cardItemInfoList

   */

  public async getAllFormsInfo(): Promise<CardItemInfo[]> {

    const formList = await formManagerAbility.getAllFormsInfo()

    const cardItemInfoList = new Array<CardItemInfo>()

    for (const formItem of formList) {

      const cardItemInfo = new CardItemInfo()

      cardItemInfo.bundleName = formItem.bundleName

      cardItemInfo.abilityName = formItem.abilityName

      cardItemInfo.moduleName = formItem.moduleName

      cardItemInfo.cardName = formItem.name

      cardItemInfo.cardDimension = formItem.defaultDimension

      cardItemInfo.description = formItem.description

      cardItemInfo.formConfigAbility = formItem.formConfigAbility

      cardItemInfo.supportDimensions = formItem.supportDimensions

      cardItemInfo.area = this.getCardSize(cardItemInfo.cardDimension)

      cardItemInfoList.push(cardItemInfo)

    }

    return cardItemInfoList

  }



  /**

   * get card area by dimension

   *

   * @param dimension

   * @return number[]

   */

  public getCardSize(dimension: number): number[] {

    if (dimension == CommonConstants.CARD_DIMENSION_1x2) {

      return this.CARD_SIZE_1x2

    } else if (dimension == CommonConstants.CARD_DIMENSION_2x2) {

      return this.CARD_SIZE_2x2

    } else if (dimension == CommonConstants.CARD_DIMENSION_2x4) {

      return this.CARD_SIZE_2x4

    } else {

      return this.CARD_SIZE_4x4

    }

  }



  /**

   * get card dimension bty area

   *

   * @param dimension

   * @return number[]

   */

  public getCardDimension(area: number[]) {

    if (area.toString() === this.CARD_SIZE_1x2.toString()) {

      return CommonConstants.CARD_DIMENSION_1x2

    } else if (area.toString() === this.CARD_SIZE_2x2.toString()) {

      return CommonConstants.CARD_DIMENSION_2x2

    } else if (area.toString() == this.CARD_SIZE_2x4.toString()) {

      return CommonConstants.CARD_DIMENSION_2x4

    } else {

      return CommonConstants.CARD_DIMENSION_4x4

    }

  }



  /**

   * get form info by bundleName

   *

   * @param bundle

   * @return Array<CardItemInfo> cardItemInfoList

   */

  public async getFormsInfoByApp(bundle: string): Promise<CardItemInfo[]> {

    Logger.info(TAG, `getFormsInfoByApp bundle: ${bundle}`)

    const formList = await formManagerAbility.getFormsInfo(bundle)

    const cardItemInfoList = new Array<CardItemInfo>()

    for (const formItem of formList) {

      const cardItemInfo = new CardItemInfo()

      cardItemInfo.bundleName = formItem.bundleName

      cardItemInfo.abilityName = formItem.abilityName

      cardItemInfo.moduleName = formItem.moduleName

      cardItemInfo.cardName = formItem.name

      cardItemInfo.cardDimension = formItem.defaultDimension

      cardItemInfo.area = this.getCardSize(cardItemInfo.cardDimension)

      cardItemInfo.description = formItem.description

      cardItemInfo.formConfigAbility = formItem.formConfigAbility

      cardItemInfo.supportDimensions = formItem.supportDimensions

      cardItemInfoList.push(cardItemInfo)

    }

    return cardItemInfoList

  }

}



export let FormManager =  new FormManagerModel()
  • 接口参考:[@ohos.app.form.formHost]

  • 桌面数据持久化存储功能模块

    • 使用关系型数据库rdb接口(系统能力:SystemCapability.DistributedDataManager.RelationalStore.Core),实现桌面数据持久化存储,存储应用的位置信息,卡片信息。
  • 源码链接:[RdbManager.ts]

/*

 * Copyright (c) 2022-2023 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */



import dataRdb from '@ohos.data.relationalStore'

import { CheckEmptyUtils } from '../utils/CheckEmptyUtils'

import { CommonConstants } from '../constants/CommonConstants'

import { GridLayoutItemInfo } from '../bean/GridLayoutItemInfo'

import { GridLayoutInfoColumns } from '../bean/GridLayoutInfoColumns'

import { Logger } from '../utils/Logger'



export const TABLE_NAME: string = 'launcher'



export const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS launcher ' +

'(id INTEGER PRIMARY KEY AUTOINCREMENT, ' +

'app_name TEXT, ' +

'appIcon_id INTEGER, ' +

'container INTEGER, ' +

'type_id INTEGER, ' +

'card_id INTEGER, ' +

'card_name TEXT, ' +

'badge_number INTEGER, ' +

'module_name TEXT, ' +

'bundle_name TEXT, ' +

'ability_name TEXT, ' +

'area TEXT, ' +

'page INTEGER, ' +

'column INTEGER, ' +

'row INTEGER)'



export const STORE_CONFIG = { name: 'launcher.db', securityLevel: dataRdb.SecurityLevel.S1 }

const TAG: string = 'RdbModel'

class RdbManagerModel {

  private mRdbStore: dataRdb.RdbStore = undefined



  constructor() {

  }



  /**

   * initRdbConfig

   *

   * @param context

   */

  async initRdbConfig(context): Promise<void> {

    Logger.info(TAG, 'initRdbConfig start')

    if (this.mRdbStore === undefined) {

      this.mRdbStore = await dataRdb.getRdbStore(context, STORE_CONFIG);

      await this.mRdbStore.executeSql(SQL_CREATE_TABLE);

      Logger.info(TAG, 'create table end');

    }

  }



  /**

   * deleteTable

   *

   * @param tableName

   */

  async deleteTable(tableName: string): Promise<void> {

    Logger.info(TAG, 'deleteTable start')

    try {

      let detelSql = `DELETE FROM ${tableName};`

      let detelSequenceSql = `UPDATE sqlite_sequence SET seq=0 WHERE name = '${tableName}';`

      await this.mRdbStore.executeSql(detelSql)

      await this.mRdbStore.executeSql(detelSequenceSql)

      Logger.debug(TAG, 'deleteTable end')

    } catch (e) {

      Logger.error(TAG, `deleteTable err: ${e}`)

    }

  }



  /**

   * insertData

   *

   * @param layoutInfo

   */

  async insertData(layoutInfo: any) {

    Logger.info(TAG, 'insertGridLayoutInfo start');

    let result: boolean = true

    if (CheckEmptyUtils.isEmpty(layoutInfo)) {

      Logger.error(TAG, 'insertGridLayoutInfo gridlayoutinfo is empty')

      result = false

      return result

    }

    try {

      // delete gridlayoutinfo table

      await this.deleteTable(TABLE_NAME)

      // insert into gridlayoutinfo

      for (let i in layoutInfo) {

        let layout = layoutInfo[i]

        for (let j in layout) {

          let element = layout[j]

          Logger.info(TAG, `insertGridLayoutInfo i= ${i}`)

          let item = {}

          if (element.typeId === CommonConstants.TYPE_APP) {

            item = {

              'app_name': element.appName,

              'bundle_name': element.bundleName,

              'module_name': element.modelName,

              'ability_name': element.abilityName,

              'appIcon_id': element.appIconId,

              'type_id': element.typeId,

              'area': element.area[0] + ',' + element.area[1],

              'page': element.page,

              'column': element.column,

              'row': element.row,

              'container': -100

            }

            let ret = await this.mRdbStore.insert(TABLE_NAME, item)

            Logger.debug(TAG, `insertGridLayoutInfo type is app ${i} ret: ${ret}`)

          } else if (element.typeId === CommonConstants.TYPE_CARD) {

            item = {

              'app_name': element.appName,

              'bundle_name': element.bundleName,

              'module_name': element.modelName,

              'ability_name': element.abilityName,

              'card_id': element.cardId,

              'card_name': element.cardName,

              'type_id': element.typeId,

              'area': element.area[0] + ',' + element.area[1],

              'page': element.page,

              'column': element.column,

              'row': element.row,

              'container': -100

            }

            let ret = await this.mRdbStore.insert(TABLE_NAME, item)

            Logger.debug(TAG, `insertGridLayoutInfo type is card ${i} ret: ${ret}`)

          }

        }

      }

    } catch (e) {

      Logger.error(TAG, `insertGridLayoutInfo error: ${e}`)

    }

    return result

  }



  async queryLayoutInfo() {

    Logger.info(TAG, 'queryLayoutInfo start')

    const resultList: GridLayoutItemInfo[] = []

    const predicates = new dataRdb.RdbPredicates(TABLE_NAME)

    predicates.equalTo(GridLayoutInfoColumns.CONTAINER, -100)

      .and().orderByAsc('page').and().orderByAsc('row').and().orderByAsc('column')

    let resultSet = await this.mRdbStore.query(predicates)

    Logger.info(TAG, `queryLayoutInfo query,count=${resultSet.rowCount}`)

    let isLast = resultSet.goToFirstRow()

    while (isLast) {

      const layoutInfo: GridLayoutItemInfo = GridLayoutItemInfo.fromResultSet(resultSet)

      resultList.push(layoutInfo)

      isLast = resultSet.goToNextRow()

    }

    resultSet.close()

    resultSet = null

    return resultList

  }



  async insertItem(item: GridLayoutItemInfo) {

    if (CheckEmptyUtils.isEmpty(item)) {

      return

    }

    let element = {

      'app_name': item.appName,

      'module_name': item.moduleName,

      'bundle_name': item.bundleName,

      'ability_name': item.abilityName,

      'appIcon_id': item.appIconId,

      'card_id': item.cardId,

      'card_name': item.cardName,

      'type_id': item.typeId,

      'area': item.area[0] + ',' + item.area[1],

      'page': item.page,

      'column': item.column,

      'row': item.row,

      'container': -100

    }

    let ret = await this.mRdbStore.insert(TABLE_NAME, element)

    Logger.debug(TAG, `insertGridLayoutInfo ret: ${ret}`)

  }



  async deleteItemByPosition(page: number, row: number, column: number) {

    const predicates = new dataRdb.RdbPredicates(TABLE_NAME);

    predicates.equalTo('page', page)

      .and().equalTo('row', row)

      .and().equalTo('column', column);

    let query = await this.mRdbStore.query(predicates);

    if (query.rowCount > 0) {

      let ret = await this.mRdbStore.delete(predicates);

      Logger.debug(TAG, `deleteItem ret: ${ret}`);

    }

  }

}



export let RdbManager = new RdbManagerModel()
  • 接口参考:[@ohos.data.relationalStore]

  • 加锁、解锁、清理后台任务功能模块

    • 使用missionManager模块接口(系统能力:SystemCapability.Ability.AbilityRuntime.Mission),获取最近任务信息,并实现加锁、解锁、清理后台任务的功能。
    • 源码链接:[MissionModel.ts]
    • 接口参考:[@ohos.application.missionManager]
  • 点击桌面应用拉起最近任务至前台功能模块

    • 使用ServiceExtensionContext模块的startRecentAbility接口(系统能力:SystemCapability.Ability.AbilityRuntime.Core),拉起最近任务至前台显示,若应用Ability未启动时,则拉起新创建的应用Ability显示到前台。 源码链接:[LauncherAbilityManager.ts]
 
/*

 * Copyright (c) 2022-2023 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */



import installer from '@ohos.bundle.installer';

import launcherBundleManager from '@ohos.bundle.launcherBundleManager';

import bundleMonitor from '@ohos.bundle.bundleMonitor';

import osAccount from '@ohos.account.osAccount'

import { AppItemInfo } from '../bean/AppItemInfo'

import { CheckEmptyUtils } from '../utils/CheckEmptyUtils'

import { CommonConstants } from '../constants/CommonConstants'

import { EventConstants } from '../constants/EventConstants'

import { ResourceManager } from './ResourceManager'

import { Logger } from '../utils/Logger'

import type { BusinessError } from '@ohos.base';



const TAG: string = 'LauncherAbilityManager'



/**

 * Wrapper class for innerBundleManager and formManager interfaces.

 */

export class LauncherAbilityManager {

  private static readonly BUNDLE_STATUS_CHANGE_KEY_REMOVE = 'remove'

  private static readonly BUNDLE_STATUS_CHANGE_KEY_ADD = 'add'

  private static launcherAbilityManager: LauncherAbilityManager = undefined

  private readonly mAppMap = new Map<string, AppItemInfo>()

  private mResourceManager: ResourceManager = undefined

  private readonly mLauncherAbilityChangeListeners: any[] = []

  private mUserId: number = 100

  private context: any = undefined



  constructor(context) {

    this.context = context

    this.mResourceManager = ResourceManager.getInstance(context)

    const osAccountManager = osAccount.getAccountManager()

    osAccountManager.getOsAccountLocalIdFromProcess((err, localId) => {

      Logger.debug(TAG, `getOsAccountLocalIdFromProcess localId ${localId}`)

      this.mUserId = localId

    })

  }



  /**

   * Get the application data model object.

   *

   * @return {object} application data model singleton

   */

  static getInstance(context): LauncherAbilityManager {

    if (this.launcherAbilityManager === null || this.launcherAbilityManager === undefined) {

      this.launcherAbilityManager = new LauncherAbilityManager(context)

    }

    return this.launcherAbilityManager

  }



  /**

   * get all app List info from BMS

   *

   * @return 应用的入口Ability信息列表

   */

  async getLauncherAbilityList(): Promise<AppItemInfo[]> {

    Logger.info(TAG, 'getLauncherAbilityList begin')

    let abilityList = await launcherBundleManager.getAllLauncherAbilityInfo(this.mUserId)

    const appItemInfoList = new Array<AppItemInfo>()

    if (CheckEmptyUtils.isEmpty(abilityList)) {

      Logger.info(TAG, 'getLauncherAbilityList Empty')

      return appItemInfoList

    }

    for (let i = 0; i < abilityList.length; i++) {

      let appItem = await this.transToAppItemInfo(abilityList[i])

      appItemInfoList.push(appItem)

    }

    return appItemInfoList

  }



  /**

   * get AppItemInfo from BMS with bundleName

   * @params bundleName

   * @return AppItemInfo

   */

  async getAppInfoByBundleName(bundleName: string): Promise<AppItemInfo | undefined> {

    let appItemInfo: AppItemInfo | undefined = undefined

    // get from cache

    if (this.mAppMap != null && this.mAppMap.has(bundleName)) {

      appItemInfo = this.mAppMap.get(bundleName)

    }

    if (appItemInfo != undefined) {

      Logger.info(TAG, `getAppInfoByBundleName from cache: ${JSON.stringify(appItemInfo)}`)

      return appItemInfo

    }

    // get from system

    let abilityInfos = await launcherBundleManager.getLauncherAbilityInfo(bundleName, this.mUserId)

    if (abilityInfos == undefined || abilityInfos.length == 0) {

      Logger.info(TAG, `${bundleName} has no launcher ability`)

      return undefined

    }

    let appInfo = abilityInfos[0]

    const data = await this.transToAppItemInfo(appInfo)

    Logger.info(TAG, `getAppInfoByBundleName from BMS: ${JSON.stringify(data)}`)

    return data

  }



  private async transToAppItemInfo(info): Promise<AppItemInfo> {

    const appItemInfo = new AppItemInfo()

    appItemInfo.appName = await this.mResourceManager.getAppNameSync(

    info.labelId, info.elementName.bundleName, info.applicationInfo.label

    )

    appItemInfo.isSystemApp = info.applicationInfo.systemApp

    appItemInfo.isUninstallAble = info.applicationInfo.removable

    appItemInfo.appIconId = info.iconId

    appItemInfo.appLabelId = info.labelId

    appItemInfo.bundleName = info.elementName.bundleName

    appItemInfo.abilityName = info.elementName.abilityName

    await this.mResourceManager.updateIconCache(appItemInfo.appIconId, appItemInfo.bundleName)

    this.mAppMap.set(appItemInfo.bundleName, appItemInfo)

    return appItemInfo

  }





  /**

   * 启动应用

   *

   * @params paramAbilityName Ability名

   * @params paramBundleName 应用包名

   */

  startLauncherAbility(paramAbilityName, paramBundleName) {

    Logger.info(TAG, `startApplication abilityName: ${paramAbilityName}, bundleName: ${paramBundleName}`)

    this.context.startAbility({

      bundleName: paramBundleName,

      abilityName: paramAbilityName

    }).then(() => {

      Logger.info(TAG, 'startApplication promise success')

    }, (err) => {

      Logger.error(TAG, `startApplication promise error: ${JSON.stringify(err)}`)

    })

  }



  /**

   * 通过桌面图标启动应用

   *

   * @params paramAbilityName Ability名

   * @params paramBundleName 应用包名

   */

  startLauncherAbilityFromRecent(paramAbilityName, paramBundleName): void {

    Logger.info(TAG, `startApplication abilityName: ${paramAbilityName}, bundleName: ${paramBundleName}`);

    this.context.startRecentAbility({

      bundleName: paramBundleName,

      abilityName: paramAbilityName

    }).then(() => {

      Logger.info(TAG, 'startApplication promise success');

    }, (err) => {

      Logger.error(TAG, `startApplication promise error: ${JSON.stringify(err)}`);

    });

  }



  /**

   * 卸载应用

   *

   * @params bundleName 应用包名

   * @params callback 卸载回调

   */

  async uninstallLauncherAbility(bundleName: string, callback): Promise<void> {

    Logger.info(TAG, `uninstallLauncherAbility bundleName: ${bundleName}`);

    const bundlerInstaller = await installer.getBundleInstaller();

    bundlerInstaller.uninstall(bundleName, {

      userId: this.mUserId,

      installFlag: 0,

      isKeepData: false

    }, (err: BusinessError) => {

      Logger.info(TAG, `uninstallLauncherAbility result => ${JSON.stringify(err)}`);

      callback(err);

    })

  }



  /**

   * 开始监听系统应用状态.

   *

   * @params listener 监听对象

   */

  registerLauncherAbilityChangeListener(listener: any): void {

    if (!CheckEmptyUtils.isEmpty(listener)) {

      if (this.mLauncherAbilityChangeListeners.length == 0) {

        bundleMonitor.on(LauncherAbilityManager.BUNDLE_STATUS_CHANGE_KEY_ADD, (bundleChangeInfo) => {

          Logger.debug(TAG, `mBundleStatusCallback add bundleName: ${bundleChangeInfo.bundleName},

            userId: ${bundleChangeInfo.userId}, mUserId ${this.mUserId}`)

          if (this.mUserId === bundleChangeInfo.userId) {

            this.notifyLauncherAbilityChange(EventConstants.EVENT_PACKAGE_ADDED,

              bundleChangeInfo.bundleName, bundleChangeInfo.userId)

          }

        })

        bundleMonitor.on(LauncherAbilityManager.BUNDLE_STATUS_CHANGE_KEY_REMOVE, (bundleChangeInfo) => {

          Logger.debug(TAG, `mBundleStatusCallback remove bundleName: ${bundleChangeInfo.bundleName},

            userId: ${bundleChangeInfo.userId}, mUserId ${this.mUserId}`)

          if (this.mUserId === bundleChangeInfo.userId) {

            this.notifyLauncherAbilityChange(EventConstants.EVENT_PACKAGE_REMOVED,

              bundleChangeInfo.bundleName, bundleChangeInfo.userId)

          }

          AppStorage.Set('isRefresh', true)

        })

      }

      const index = this.mLauncherAbilityChangeListeners.indexOf(listener)

      if (index == CommonConstants.INVALID_VALUE) {

        this.mLauncherAbilityChangeListeners.push(listener)

      }

    }

  }



  /**

   * 取消监听系统应用状态.

   *

   * @params listener 监听对象

   */

  unregisterLauncherAbilityChangeListener(listener: any): void {

    if (!CheckEmptyUtils.isEmpty(listener)) {

      const index = this.mLauncherAbilityChangeListeners.indexOf(listener)

      if (index != CommonConstants.INVALID_VALUE) {

        this.mLauncherAbilityChangeListeners.splice(index, 1)

      }

      if (this.mLauncherAbilityChangeListeners.length == 0) {

        bundleMonitor.off(LauncherAbilityManager.BUNDLE_STATUS_CHANGE_KEY_ADD)

        bundleMonitor.off(LauncherAbilityManager.BUNDLE_STATUS_CHANGE_KEY_REMOVE)

      }

    }

  }



  private notifyLauncherAbilityChange(event: string, bundleName: string, userId: number): void {

    for (let index = 0; index < this.mLauncherAbilityChangeListeners.length; index++) {

      this.mLauncherAbilityChangeListeners[index](event, bundleName, userId)

    }

  }

}

接口参考:[@ohos.app.ability.ServiceExtensionAbility]

鸿蒙开发岗位需要掌握那些核心要领?

目前还有很多小伙伴不知道要学习哪些鸿蒙技术?不知道重点掌握哪些?为了避免学习时频繁踩坑,最终浪费大量时间的。

自己学习时必须要有一份实用的鸿蒙(Harmony NEXT)资料非常有必要。 这里我推荐,根据鸿蒙开发官网梳理与华为内部人员的分享总结出的开发文档。内容包含了:【ArkTS、ArkUI、Stage模型、多端部署、分布式应用开发、音频、视频、WebGL、OpenHarmony多媒体技术、Napi组件、OpenHarmony内核、Harmony南向开发、鸿蒙项目实战】等技术知识点。

废话就不多说了,接下来好好看下这份资料。

如果你是一名Android、Java、前端等等开发人员,想要转入鸿蒙方向发展。可以直接领取这份资料辅助你的学习。鸿蒙OpenHarmony知识←前往。下面是鸿蒙开发的学习路线图。

针对鸿蒙成长路线打造的鸿蒙学习文档。鸿蒙(OpenHarmony )学习手册(共计1236页)与鸿蒙(OpenHarmony )开发入门教学视频,帮助大家在技术的道路上更进一步。

其中内容包含:

《鸿蒙开发基础》鸿蒙OpenHarmony知识←前往

  1. ArkTS语言
  2. 安装DevEco Studio
  3. 运用你的第一个ArkTS应用
  4. ArkUI声明式UI开发
  5. .……

《鸿蒙开发进阶》鸿蒙OpenHarmony知识←前往

  1. Stage模型入门
  2. 网络管理
  3. 数据管理
  4. 电话服务
  5. 分布式应用开发
  6. 通知与窗口管理
  7. 多媒体技术
  8. 安全技能
  9. 任务管理
  10. WebGL
  11. 国际化开发
  12. 应用测试
  13. DFX面向未来设计
  14. 鸿蒙系统移植和裁剪定制
  15. ……

《鸿蒙开发实战》鸿蒙OpenHarmony知识←前往

  1. ArkTS实践
  2. UIAbility应用
  3. 网络案例
  4. ……

最后

鸿蒙是完全具备无与伦比的机遇和潜力的;预计到年底将有 5,000 款的应用完成原生鸿蒙开发,这么多的应用需要开发,也就意味着需要有更多的鸿蒙人才。鸿蒙开发工程师也将会迎来爆发式的增长,学习鸿蒙势在必行!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1607170.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Arcgis Pro2.5安装教程(内含安装文件)

​最近处理的数据量大&#xff0c;发现arcmap这种老产品属实是不行了&#xff0c;相比于下一代的Arcgis Pro,不但运行速度慢&#xff0c;也容易遇到突然关闭的问题&#xff0c;之前基于团队的选择也没办法&#xff0c;最近实在是被数据搞得无语了&#xff0c;一鼓作气装上了Arc…

武汉星起航:亚马逊上的中国智慧,创新与差异化策略赢得全球赞誉

在全球电商的浪潮中&#xff0c;亚马逊作为行业的佼佼者&#xff0c;为众多商家提供了一个展示自我、实现价值的舞台。在这其中&#xff0c;中国商家以其独特的创新和差异化策略&#xff0c;逐渐在亚马逊平台上崭露头角&#xff0c;赢得了全球消费者的青睐。 中国商家在亚马逊…

新手入门:大语言模型训练指南

在这个信息爆炸的时代&#xff0c;人工智能技术正以前所未有的速度渗透到我们生活的方方面面。从智能手机上的语音助手到自动驾驶汽车&#xff0c;AI的应用无处不在。而在这些令人惊叹的技术背后&#xff0c;大语言模型&#xff08;LLM&#xff09;扮演着至关重要的角色。它们不…

(六)Pandas文本数据 学习简要笔记 #Python #CDA学习打卡

一. 文本数据简介 1&#xff09;定义 指不能参与算术运算的任何字符&#xff0c;也称为字符型数据。如英文字母、汉字、不作为数值使用的数字(以单引号开头)和其他可输入的字符。 文本数据虽不能参加算术运算&#xff0c;但其具有纬度高、量大且语义复杂等特点&#xff0c;因…

企业微信扫码登录遇到的bug及解决办法

企业微信自建应用扫码登录 1.基本配置 1.登录企业微信管理系统&#xff0c;新建一个自建应用 2.点击你新建的应用&#xff0c;拿到AgentId 3.在我的企业页面拿到appid 4.配置可信域名 5.配置授权回调域 写到这&#xff0c;基本配置已完成&#xff0c;可以开始写前端代码 …

【高级RAG技巧】在大模型知识库问答中增强文档分割与表格提取

前言 文档分割是一项具有挑战性的任务&#xff0c;它是任何知识库问答系统的基础。高质量的文档分割结果对于显著提升问答效果至关重要&#xff0c;但是目前大多数开源库的处理能力有限。 这些开源的库或者方法缺点大致可以罗列如下&#xff1a; 只能处理文本&#xff0c;无法…

MySql8快速迁移版的制作过程

首先说明&#xff0c;mysql 8的安装不同与mysql5.x。 做程序的朋友都知道&#xff0c;程序好做&#xff0c;客户难伺候&#xff0c;因为限于用户的情况&#xff0c;如何能让用户把程序运行起来很关键&#xff0c;比如日前我在做 山东高中信息技术 学考 考前练习 系统时&#x…

解决 vue install 引发的 failed Error: not found: python2 问题

发生 install 异常时&#xff0c;提示信息如下所示&#xff1a; npm ERR! code 1 npm ERR! path U:\cnblogs\fanfengping-dtops\fanfengping-dtops-front\node_modules\node-sass npm ERR! command failed npm ERR! command U:\Windows\system32\cmd.exe /d /s /c node scripts…

苍穹外卖学习笔记(5.微信登录,商品浏览)

目录 一、微信登录1、封装HttpClient工具类2、导入小程序代码3、微信登录流程4、需求分析设计5、代码开发6、功能测试 二、商品浏览1、需求分析设计2、代码开发1.查询分类2.根据分类id查询套餐3.根据分类id查询套餐&#xff0c;根据套餐id查询包含菜品 3、测试 四、相关知识1、…

Django模型的字段类型

Django模型中最重要并且也是唯一必须执行的就是字段定义。字段在类中进行定义&#xff0c;对应于实体数据库的字段。另外&#xff0c;定义模型字段名时为了避免冲突&#xff0c;不建议使用模型API中已经定义的关键字。 字段类型用以指定数据库的数据类型&#xff0c;例如Integ…

python入门之简洁安装VS保姆版安装(含虚拟环境)

11、保姆版安装 Anoconda安装&#xff08;python的一个发行版本&#xff09; 优点&#xff1a;集成了许多关于python科学计算的第三方库&#xff0c;保姆级别 下载&#xff1a;www.anaconda.com/download/ 版本默认64位&#xff0c;py37 √&#xff1a;add anaconda to my…

代码随想录算法训练营第三十八天|509. 斐波那契数,70.爬楼梯,746. 使用最小花费爬楼梯

动态规划(DP) 如果某一问题有很多重叠子问题&#xff0c;使用动态规划是最有效的。 所以动态规划中每一个状态一定是由上一个状态推导出来的 一、动态规划包含哪些问题&#xff1f; 1、基础问题&#xff0c;如斐波那契数 2、背包问题&#xff0c;很经典的问题 3、打家劫舍 4、…

操作系统命令(贪吃蛇项目)

&#x1f3dd;1.获得句柄 GetStdHandle是⼀个Windows API函数。它用于从⼀个特定的标准设备&#xff08;标准输入、标准输出或标 准错误&#xff09;中取得⼀个句柄&#xff08;用来标识不同设备的数值&#xff09;&#xff0c;使用这个句柄可以操作设备。 ⛳️函数原型&…

Git使用总结(不断更新中)

branch 本地分支操作 删除本地分支 git branch -d <local-branch-name>远端分支操作 从远端分支创建本地分支 git checkout -b <local-branch-name> origin/<remote-branch-name>git ignore 如果工程的代码文件中有不希望上传到远端的文件&#xff0c;…

【Linux学习】Linux权限管理(一)

文章标题 &#x1f680;Linux用户分类&#x1f680;Linux权限管理&#x1f680;文件访问者的分类&#xff08;人&#xff09;&#x1f680;文件类型和访问权限&#xff08;事物属性&#xff09;&#x1f680;怎么修改权限 &#x1f680;Linux用户分类 Linux下有两种用户&#…

使用Hugo、Github Pages搭建自己的博客

文章目录 搭建博客框架及对比使用Hugo搭建博客使用Github Pages部署博客 搭建博客框架及对比 在众多的博客框架中&#xff0c;Hugo、Jekyll和Hexo因其出色的性能和易用性而备受推崇。 特点HugoJekyllHexo速度极高中等较高易用性高中等高&#xff08;熟悉JavaScript者&#xf…

力扣112,路径总和

给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径&#xff0c;这条路径上所有节点值相加等于目标和 targetSum 。如果存在&#xff0c;返回 true &#xff1b;否则&#xff0c;返回 false 。 叶子节点 是指没有子节点…

怎样实现opc采集数据后传给web后端

现在很多老工厂要进行数字化改造&#xff0c;现场生产的各种数据需要传到web后端&#xff0c;很多工厂现场原有的自动监控系统已经采集了现场的各种数据&#xff0c;只是没有形成联网。如果前端自动化系统全部废除&#xff0c;重新做数字化控制系统&#xff0c;成本投入太大&am…

GIS地理信息平台+智慧巡检技术解决方案(Word原件)

1.系统概述 1.1.需求描述 1.2.需求分析 1.3.重难点分析 1.4.重难点解决措施 2.系统架构设计 2.1.系统架构图 2.2.关键技术 3.系统功能设计 3.1.功能清单列表软件全套精华资料包清单部分文件列表&#xff1a; 工作安排任务书&#xff0c;可行性分析报告&#xff0c;立项…

风速Weibull分布和光伏Beta分布的参数拟合方法(含matlab算例)

在风光场景生成、随机优化调度等研究中&#xff0c;常常假设风速服从Weibull分布&#xff0c;太阳辐照度服从Beta分布。那我们如何得到两个分布的参数呢&#xff1f;文本首先介绍了风速Weibull分布和辐照度Beta分布的基本概率模型及其性性质&#xff0c;之后以MATLAB代码为例阐…