在 nativescvript-vue 中处理 android 后退按钮

Handling android back button in nativescvript-vue

我正在尝试在 nativescript-vue 中构建一个包含音频内容的应用程序。我有一个函数,当页面为 mounted():

时被调用
this.player = new TNSPlayer();
const playerOptions = {
    audioFile: this.audioLink,
    loop: false,
    autoplay: false,
};

this.player
    .initFromUrl(playerOptions)
    .then((res) => {
        console.log(res);
    })
    .catch((err) => {
        console.log("something went wrong...", err);
    });

this.checkInterval = setInterval(() => {
    this.player.getAudioTrackDuration().then(duration => {
        // iOS: duration is in seconds
        // Android: duration is in milliseconds
        let current = this.player.currentTime
        if (isIOS) {
            duration *= 1000
            current *= 1000
        }

        this.currentTime = current;
        this.totalTime = duration;
        this.progress = Math.ceil(current / duration * 100);

        this.isPlaying = this.player.isAudioPlaying()
    });
}, 200)

我需要知道音频播放器何时准备就绪,以便我可以显示 play/pause 按钮。我还需要检查按下 android 的后退按钮时调用的事件。

目前,即使单击 android 中的后退按钮,我的音频仍会继续播放。我想 stop/pause 播放器按下后退按钮。

编辑: 我试过这个:

var applicationModule = require("application");
var AndroidApplication = applicationModule.android;
var activity = AndroidApplication.foregroundActivity;

activity.onBackPressed = function () {
    console.log('Back button pressed.')
};

但这会引发错误 onBackPressed 未找到。

TypeError: Cannot set property 'onBackPressed' of undefined

使用 Vuex,我会尝试将 player 放入商店,然后在返回按下事件中停止它。

app.js:

if (application.android) {
    application.android.on(application.AndroidApplication.activityBackPressedEvent, function() {
        // commit or dispatch stop player
    );
}