天天看點

OpenHarmony之如何實作震動。

OpenHarmony之如何實作震動。

作者“堅果,華為雲享專家,InfoQ簽約作者,潤和軟體KOL專家,電子發燒友鴻蒙MVP,51CTO部落格專家部落客,阿裡雲部落格專家,開源項目gin-vue-admin成員之一

馬達振動服務通過細膩精緻的一體化振動體驗和差異化體驗,提升使用者互動效率和易用性、提升使用者體驗。

運作機制

Vibrator屬于控制類小器件,主要包含以下四個子產品:Vibrator API,Vibrator Framework,Vibrator Service和HDF層。

控制類小器件中的Vibrator

OpenHarmony之如何實作震動。
  • Vibrator API:提供振動器基礎的API,主要包含振動器的清單查詢,振動器的振動器效果查詢,觸發/關閉振動器等接口。
  • Vibrator Framework:實作振動器的架構層管理,實作與控制類小器件Service的通信。
  • Vibrator Service:實作控制器的服務管理。
  • HDF層:适配不同裝置。

接下來我們就看一下如何實作一個簡單的震動器。

效果預覽

OpenHarmony之如何實作震動。

1.配置權限

"reqPermissions": [
      {
        "name": "ohos.permission.VIBRATE"
      }
    ]      

2. 導入子產品

import vibrator from '@ohos.vibrator';      
function vibrate(duration: number, callback?: AsyncCallback<void>): void;      

3.觸發裝置振動。

vibrator.vibrate(10000, (error) => {
                if (error) {//調用失敗,列印error.code和error.message
                  console.info("Promise return failed.error.code " + error.code + "error.message " + error.message);
                  this.cnotallow="失敗"
                } else { //調用成功,裝置開始振動
                  console.info("Promise returned to indicate a successful vibration.")
                  this.cnotallow="成功"

                }


              }      

完整代碼

/**     
  * @ProjectName : nutsStudy
  * @FileName :  viberation
  * @Author : 堅果
  * @Time : 2022/8/15 11:15
  * @Description : 震動
 */
import vibrator from "@ohos.vibrator"

@Entry
@Component
struct ViberSample {
  @State content: string = "是否震動";

  build() {

    Column() {


      Button(this.content)
        .width(200)
        .height(80)
        .fontSize(30)
        .fontColor(Color.Orange)
        .onClick(() => {


          vibrator.vibrate(10000, (error) => {
            if (error) { //調用失敗,列印error.code和error.message
              console.info("Promise return failed.error.code " + error.code + "error.message " + error.message);
              this.content = "失敗"
            } else { //調用成功,裝置開始振動
              console.info("Promise returned to indicate a successful vibration.")
              this.content = "成功"
            }
          }

          )
        }
        )



    }.width("100%").height("100%").justifyContent(FlexAlign.Center)
  }
}      

繼續閱讀