HarmonyOS鸿蒙Next中快应用之onBackPress的多重运用指导

HarmonyOS鸿蒙Next中快应用之onBackPress的多重运用指导 【关键字】
onBackPress、退出、弹框

【背景介绍】
快应用推出了onBackPress页面生命周期,可以让开发者自定义返回的逻辑,这里就来介绍下关于onBackPress生命周期的两种运用方式。

【经验总结】
这里实现了以下两种:

一、退出时弹出弹框让用户确认是退出还是继续浏览,同时里面也可以展示一下广告。

1、弹框的实现主要是用到了stack组件的堆叠,以及if属性来控制展示与隐藏。

<stack style="width: 100%; height: 100%">
  <div class="item-container" style="width: 100%; height: 100%">
    <text class="txt">测试文字</text>
  </div>
  <div class="componentdiv" if="{{display}}">
    <div if="native.isShow">
      <stack class="stackstyle" onclick="reportNativeClick()">
        <image if="native.isShowImg" class="img" src="{{native.adImgSrc}}"></image>
        <ad-button class="adbtn" onclick="startButton()" valuetype="0" adunitid="{{native.adUnitId}}" adid="{{native.adData.adId}}"></ad-button>
      </stack>
    </div>
    <div>
      <input class="btn" type="button" value="exit" onclick="exit" />
      <input class="btn" type="button" value="continue" onclick="resume" />
    </div>
  </div>
</stack>

2、onbackpress逻辑实现,设置if为true展示弹框,并调用truethis.showNativeAd();请求并展示广告。

onBackPress() {
  console.log("quit!!!");
  var that = this;
  that.display = true;
  this.showNativeAd();
  if (this.native.isShow) {
    this.reportNativeShow();
  }
  return true;
},

3、弹框按钮的实现。

exit() {
  this.$app.exit()
},
resume() {
  nativeAd.destroy();
  this.display = false;
}

截图:

cke_6754.png

Demo代码:

<template>
  <div class="container">
    <stack style="width: 100%; height: 100%">
      <div class="item-container" style="width: 100%; height: 100%">
        <text class="txt">测试文字</text>
      </div>
      <div class="componentdiv" if="{{display}}">
        <div if="native.isShow">
          <stack class="stackstyle" onclick="reportNativeClick()">
            <image if="native.isShowImg" class="img" src="{{native.adImgSrc}}"></image>
            <ad-button class="adbtn" onclick="startButton()" valuetype="0" adunitid="{{native.adUnitId}}" adid="{{native.adData.adId}}"></ad-button>
          </stack>
        </div>
        <div>
          <input class="btn" type="button" value="exit" onclick="exit" />
          <input class="btn" type="button" value="continue" onclick="resume" />
        </div>
      </div>
    </stack>
  </div>
</template>

<style>
  .container {
    flex: 1;
    flex-direction: column;
    width: 100%;
    height: 100%;
  }
  /* 其他样式略 */
</style>

<script>
  import ad from '@service.ad';
  let nativeAd;
  export default {
    data: {
      display: false,
      native: {
        adUnitId: "testb65czjivt9",
        isShow: false,
        adData: {},
        isShowImg: true,
        isShowVideo: true,
        errStr: "",
        btnTxt: "",
        adImgSrc: "https://cs02-pps-drcn.dbankcdn.com/cc/creative/upload/20191226/b750592e-04be-4132-9971-52494b1e5b43.jpg",
      }
    },
    onInit: function () {
      this.$page.setTitleBar({ text: 'notification' })
    },
    onBackPress() {
      console.log("quit!!!");
      var that = this
      that.display = true
      this.showNativeAd();
      if (this.native.isShow) {
        this.reportNativeShow();
      }
      return true;
    },
    exit() {
      this.$app.exit()
    },
    resume() {
      nativeAd.destroy();
      this.display = false;
    },
    isDownloadAd(creativeType) {
      let downloadTypes = [103, 106, 107, 108, 101, 102, 110];
      return downloadTypes.includes(creativeType);
    },
    showNativeAd() {
      var that = this;
      nativeAd = ad.createNativeAd({ adUnitId: this.native.adUnitId });
      nativeAd.onLoad(data => {
        console.info("ad data loaded: " + JSON.stringify(data));
        this.native.adData = data.adList[0];
        if (this.native.adData) {
          if (this.native.adData.imgUrlList) {
            this.native.adImgSrc = this.native.adData.imgUrlList[0];
            console.info(" this.native.adImgSrc =" + this.native.adImgSrc);
            this.native.isShowImg = true;
          } else {
            this.native.isShowImg = false;
            this.native.adImgSrc = "";
          }
          if (this.native.adData.clickBtnTxt) {
            this.native.btnTxt = this.native.adData.clickBtnTxt;
          } else {
            this.native.btnTxt = "";
          }
          if (this.native.adData.videoUrlList && this.native.adData.videoUrlList[0]) {
            this.native.adVideoSrc = this.native.adData.videoUrlList[0];
            this.native.isShowVideo = true;
          } else {
            this.native.isShowVideo = false;
            this.native.adVideoSrc = "";
          }
          this.native.isShow = true;
          this.native.errStr = "";
          this.reportNativeShow();
        }
      });
      nativeAd.onError(e => {
        console.error("load ad error:" + JSON.stringify(e));
        this.native.isShowImg = false;
        this.native.isShowVideo = false;
        this.native.isShow = false;
        this.native.errStr = JSON.stringify(e);
      });
      nativeAd.load();
    },
    reportNativeShow() {
      if (nativeAd) {
        nativeAd.reportAdShow({ adId: this.native.adData.adId });
      }
    },
    reportNativeClick() {
      nativeAd.reportAdClick({
        adId: this.native.adData.adId
      });
    },
    listenNativeAdDownloadStatus(downloadstatus) {
      if (downloadstatus === "INSTALLED") {
        this.native.btnTxt = "OPEN";
      }
    },
    startButton(event) {
      console.error('start download result is = ', event.resultCode)
    },
    removeAdListen: function () {
      if (nativeAd) {
        nativeAd.offDownloadProgress();
        nativeAd.offError(() => {
          console.log("nativeAd offError");
        });
        nativeAd.offLoad(() => {
          console.log("nativeAd offLoad");
        });
        nativeAd.offStatusChanged();
      }
    },
    onDestroy() {
      if (nativeAd) {
        nativeAd.destroy();
      }
    },
    closeAd: function () {
      this.native.isShow = false;
    } 
  }
</script>

二、弹框提示加桌功能实现,增加用户留存。

实现代码:

onBackPress() {
  var that = this
  console.info(`Triggered:onBackPress`);
  prompt.showMessageDialog({
    message: '确定退出不再继续浏览了吗?',
    buttons: [
      {
        text: '添加至桌面',
        color: '#33dd44'
      },
      {
        text: '继续退出',
        color: '#33dd44'
      }
    ],
    success: function (data) {
      console.log("handling success", data.index);
      if (data.index === 0) {
        shortcut.install({
          message: '',
          success: function (ret) {
            console.log('handling success: ' + ret);
            that.$app.exit()
          }
        })
      } else {
        that.$app.exit()
      }
    },
  })
  return true
}

截图:

cke_17793.png


更多关于HarmonyOS鸿蒙Next中快应用之onBackPress的多重运用指导的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于HarmonyOS鸿蒙Next中快应用之onBackPress的多重运用指导的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,onBackPress是快应用生命周期中的一个重要回调函数,用于处理用户按下返回键时的行为。开发者可以通过重写onBackPress来实现自定义的返回逻辑,例如:

  • 页面导航:在返回时跳转到指定页面,而不是直接退出应用。
  • 数据保存:在返回前保存用户输入的数据,防止数据丢失。
  • 弹窗提示:显示确认弹窗,询问用户是否确定退出当前操作。
  • 阻止返回:在某些条件下阻止返回操作,确保用户完成必要步骤。

通过合理运用onBackPress,可以提升用户体验并确保应用流程的完整性。

回到顶部