Background Services in Mono for Android: Listing 3

The startPlaying() and stopPlaying() methods.

private void startPlaying()
    {
        if (_player != null && _player.IsPlaying)
            return;

        _player = MediaPlayer.Create(this, Resource.Raw.NIN);
        _player.Start();
        _player.Completion += (sender, e) => StopSelf();

        var notificationService = (NotificationManager) GetSystemService(NotificationService);
        var notification = new Notification(Resource.Drawable.Icon, "Music started",
                                            Java.Lang.JavaSystem.CurrentTimeMillis());
        notification.Flags = NotificationFlags.NoClear;
        
        var notificationIntent = PendingIntent.GetActivity(this, 0, new Intent(this, typeof(MusicActivity)), 0);
        notification.SetLatestEventInfo(this, "Now Playing", "Nine Inch Nails - 7 Ghosts I", notificationIntent);

        notificationService.Notify(MusicPlayingNotification, notification);
    }

    private void stopPlaying()
    {
        if (_player == null || !_player.IsPlaying)
            return;

        _player.Stop();
        _player.Release();
        _player = null;

        var notificationService = (NotificationManager)GetSystemService(NotificationService);
        notificationService.Cancel(MusicPlayingNotification);
    }

About the Author

Greg Shackles, Microsoft MVP, Xamarin MVP, is a Principal Engineer at Olo. He hosts the Gone Mobile podcast, organizes the NYC Mobile .NET Developers Group, and wrote Mobile Development with C# (O'Reilly). Greg is obsessed with heavy metal, baseball, and craft beer (he’s an aspiring home brewer). Contact him at Twitter @gshackles.