Nitish Kumar
Nitish Kumar

Reputation: 6276

Handling android back button in nativescvript-vue

I'm trying to build an application in nativescript-vue which has audio contents. I've a function which is being called when the page is 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)

I need to know when the audio player is prepared so that I can display play/pause button. Also I need to check for event which is being called when back button from android is pressed.

Currently my audio continues to play even if back button from android is clicked. I want to stop/pause the player as the back button is pressed.

Edit: I tried this:

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

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

but this throws error onBackPressed not found.

TypeError: Cannot set property 'onBackPressed' of undefined

Upvotes: 0

Views: 1558

Answers (1)

TomG
TomG

Reputation: 538

Using Vuex, I would try putting player in the store and then stopping it inside the back pressed event.

app.js:

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

Upvotes: 2

Related Questions