HarmonyOS鸿蒙Next中【快应用】视频如何根据网络状态播放和暂停

HarmonyOS鸿蒙Next中【快应用】视频如何根据网络状态播放和暂停 【关键词】

  • 视频
  • 网络
  • 播放与暂停

【现象描述】

如今丰富的流媒体时代需要消耗大量的流量,因此需要实现的功能是:

在WiFi环境下,可以实现视频的自动播放;切换到移动网络时,需要暂停视频播放,必须用户手动操作才能继续播放。

【实现方法】

  1. 可以通过network.subscribe接口全局监听网络状态的变化,获取网络状态的回调。

  2. 获取回调信息后,判断当前环境是WiFi还是移动网络,从而对video组件进行播放/暂停控制。

详细示例代码如下。

app.ux代码:

<script>
import network from '@system.network';
module.exports = {
  onCreate() {
    console.info('Application onCreate');
    this.listenNetwork();
  },
  onDestroy() {
    console.info('Application onDestroy');
    network.unsubscribe();
  },
  listenNetwork: function() {
    console.info("listenNetwork START ");
    var that = this;
    network.subscribe({
      callback: function(ret) {
        that.data.localeData.currentType = ret.type;
        console.info("listenNetwork CALLBACK :" + that.data.localeData.currentType);
      },
      fail: function(erromsg, errocode) {
        console.log('network.subscribe----------' + errocode + ': ' + erromsg)
      }
    })
  },
  data: {
    localeData: {
      currentType: ''
    }
  }
}
</script>
hello.ux代码:
<template>
  <div class="container">
    <text class="title">Network Type:{{currentType.currentType}}</text>
    <video id="video" style="height: 50%;width: 100%;" src="../Common/demo.mp4"></video>
  </div>
</template>

<style>
.container {
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.title {
  font-size: 40px;
}
</style>

<script>
import prompt from '@system.prompt';
module.exports = {
  data: {
    componentData: {},
    currentType: {}
  },
  onInit() {
    this.$page.setTitleBar({
      text: 'menu',
      textColor: '#ffffff',
      backgroundColor: '#007DFF',
      backgroundOpacity: 0.5,
      menu: true
    });
    this.currentType = this.$app.$def.data.localeData;
    this.$watch('currentType.currentType', 'listenNetType');
  },
  listenNetType: function(newValue, oldValue) {
    console.info("listenNetType newValue= " + newValue + ", oldValue=" + oldValue);
    if (newValue === 'wifi') {
      this.$element("video").start();
      prompt.showToast({
        message: 'Wi-Fi, start.',
        duration: 3000,
        gravity: 'center'
      })
    } else {
      this.$element("video").pause();
      prompt.showToast({
        message: 'non Wi-Fi, pause.',
        duration: 3000,
        gravity: 'center'
      })
    }
  },
}
</script>

更多关于HarmonyOS鸿蒙Next中【快应用】视频如何根据网络状态播放和暂停的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于HarmonyOS鸿蒙Next中【快应用】视频如何根据网络状态播放和暂停的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,快应用可以通过@system.network模块获取网络状态,并根据网络类型动态调整视频播放行为。首先,使用network.getType()获取当前网络类型,如Wi-Fi、4G等;然后,根据网络类型决定是否播放或暂停视频。例如,在4G网络下可暂停视频以节省流量,或在Wi-Fi环境下自动播放。通过监听网络状态变化,实现动态调整,确保用户体验和流量优化。

回到顶部