Background Services in Mono for Android: Listing 3

The startPlaying() and stopPlaying() methods.

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

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

        var notificationService = (NotificationManager) GetSystemService(NotificationService);
        var notification = new Notification(Resource.Drawable.Icon, "Music started",
        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)

        _player = null;

        var notificationService = (NotificationManager)GetSystemService(NotificationService);

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.

comments powered by Disqus


  • Python in VS Code Adds Data Viewer for Debugging

    The January 2021 update to the Python Extension for Visual Studio Code is out with a short list of new features headed by a data viewer used while debugging.

  • GitHub Ships Enterprise Server 3.0 Release Candidate

    It's described as "the biggest ever change to Enterprise Server," with improvements to Actions, Packages, mobile, security and more.

  • Attacks on .NET Apps Grow in Number, Severity, Says Security Firm

    .NET apps were found to have more serious vulnerabilities and suffer more attacks last year, according to data gathered by Contrast Labs.

  • Microsoft Opens Up Old Win32 APIs to C# and Rust, More Languages to Come

    Microsoft is opening up old Win32 APIs long used for 32-bit Windows programming, letting coders use languages of their choice instead of the default C/C++ option.

Upcoming Events