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.

comments powered by Disqus

Featured

  • Java on Visual Studio Code Going Cloud Native

    Cloud-native development figures prominently in a new roadmap published by Microsoft's Java on Visual Studio Code dev team.

  • Speed Lines Graphic

    Quantum-Inspired Annealing Using C# or Python

    Dr. James McCaffrey of Microsoft Research explains a new idea that slightly modifies standard simulated annealing by borrowing ideas from quantum mechanics.

  • Visual Studio 2022 v17.1 Preview 3 Improves Web Tools

    Microsoft quietly shipped Visual Studio 2022 v17.1 Preview 3 with enhancements to web tools.

  • Progress Telerik Adds 20-Plus Components for Blazor, .NET MAUI and WinUI

    The R1 2022 release of Progress Telerik development tooling adds more than 20 new components to the Blazor, .NET MAUI and WinUI offerings.

Upcoming Events