I have two pages say Page1 and page2. In Page-1 I have listview and a 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 a imagebutton in page1,If I click this image button,I want to go same page which was shown earlier(page2) with same status song continues to play(it should not play from beginning).
I understand ,If I click back button,it destroys modal page.For some reason I cant use pushasync(). Is this the possible???
2 Answers
Answers 1
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>");
Answers 2
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.
0 comments:
Post a Comment