Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Navigation in Xamarin.Forms

I have two pages say Page1 and page2. In Page-1 I have a listview and an Image button(tap gesture). Here if I click listview item, it navigates to Page2 where it plays a song.

Navigation.PushModalAsync(new page2(parameter1));

Song continues to play. Then I go back to page1 by clicking back button. Then as mentioned I have an imagebutton in page1, if I click this image button, I want to go the same page which was shown earlier(page2) with same status song continues to play (it should not play from the beginning).

I understand, if I click the back button, it destroys the model page. For some reason, I can't use pushasync(). Is this possible?

like image 281
uncle_scrooge Avatar asked Apr 18 '17 13:04

uncle_scrooge


2 Answers

Would recommend not to tightly couple your audio/media player logic with your navigation logic or Page objects - especially if you want it to continue playing in the background.

Simplest approach would be to have a AudioPlayerService class that subscribes to MessengingCenter for audio player commands - such as play, pause etc. When a play command is published, it can initiate a background thread to play the audio file.

MessagingCenter.Subscribe<Page2, AudioPlayerArgs> (this, "Play", (sender, args) => {
      // initiate thread to play song
});

Now, when you navigate from page1 to page2, you can publish/send a command to the AudioPlayerService class through MessengingCenter to start playing the song. This way, any number of back-and-forth between page1 or page2 won't affect the audio player as it can ignore the play commands if it is already playing the same audio file.

MessagingCenter.Send<Page2, AudioPlayerArgs> (this, "Play", new AudioPlayerArgs("<sound file path>"));

Note: I personally avoid using MessengingCenter in my code - A better approach would be to rather introduce an interface for IAudioPlayerService with appropriate methods to play, pause etc. and use DependencyService to maintain the AudioPlayerService state as a global object (which is default behavior)

public interface IAudioPlayerService {
     bool PlayAudio(string file);
     bool PauseAudio();
     bool StopAudio();
}

[assembly: Xamarin.Forms.Dependency (typeof (IAudioPlayerService))]
public class AudioPlayerService : IAudioPlayerService {
      //implement your methods
}

And, use following code to control your audio player service in your Page/ViewModel objects.

DependencyService.Get<IAudioPlayerService>().Play("<sound file path>");
like image 142
Sharada Gururaj Avatar answered Sep 20 '22 11:09

Sharada Gururaj


You may try to pass the same instance of a global or local variable, whatever is appropriate:

var secondpage = new page2(parameter1); // Global scope.
...
Navigation.PushModalAsync(secondpage);

Hope it helps.

like image 38
asewefy Avatar answered Sep 22 '22 11:09

asewefy