Navigation in Xamarin.Forms

I have two pages: Page1 and page 2. On page-1 I have a list and a button "Image" (yellow gesture). Here, if I click on the listview element, it will go to Page2 where it plays the song.

Navigation.PushModalAsync(new page2(parameter1));

The song continues to play. Then I will return to page 1 by clicking the back button. Then, as already mentioned, I have an image button on page 1, if I click on this image button, I want to go to the same page that was shown earlier (page 2), with the same playback time (it should not be reproduced from the very beginning).

I understand that if I click the "Back" button, it will destroy the model page. For some reason I cannot use pushasync (). Is it possible?

+6
source share
2 answers

I would recommend not tightly connecting the logic of the audio / media player with the navigation logic or page objects, especially if you want it to continue to play in the background.

The easiest approach is to have an AudioPlayerService class that subscribes to the MessengingCenter for audio player commands — for example, play, pause, etc. When a play command is published, it can initiate a background stream to play an audio file.

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

, 1 2, / AudioPlayerService MessengingCenter, . , 1 . 2 , , .

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

: MessengingCenter . IAudioPlayerService , .. DependencyService AudioPlayerService ( )

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

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

Page/ViewModel.

DependencyService.Get<IAudioPlayerService>().Play("<sound file path>");
+4

, , :

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

, .

+2

Source: https://habr.com/ru/post/1016605/


All Articles