Fixed SDL2 Android App Issue When Suspending and Resuming

Months ago, I needed to update the SDL2 libraries I was using in order to gain access to a new piece of functionality in SDL2 that lets me load SVG vector graphic file and create textures out of them. But then I found a problem was introduced. The app would hang whenever I would leave it to look at a different app. I posted about it on the libSDL Discourse site, but I did not receive a response. I finally had a chance to investigate this issue and I think I have solved it.

When an SDL2-based Android app needs to suspend and resume, there are events that need to be handled immediately, before your main event loop: SDL_APP_WILLENTERBACKGROUND and SDL_APP_DIDENTERFOREGROUND.

So you create an event filter, register it with SDL_SetEventFilter(), and it is here that you need to handle things like music. If your app enters the background, but music is still playing, the app will crash. So, in your event filter, you would have code that looks something like the following:

int EventHandler::eventFilter(void * userData, SDL_Event * event)
{
    int whatToDoWithThisEvent(ADD_TO_QUEUE);

    IHardwareLayer * hardwareLayer = static_cast<IHardwareLayer *>(userData);
    if (hardwareLayer != 0) 
    { 
        switch(event->type)
        {
            case SDL_APP_WILLENTERBACKGROUND:
                {
                    hardwareLayer->pauseMusic();
                    whatToDoWithThisEvent = DO_NOT_ADD_TO_QUEUE;
                }
                break;

            case SDL_APP_DIDENTERFOREGROUND:
                { 
                    hardwareLayer->resumeMusic();
                    whatToDoWithThisEvent = DO_NOT_ADD_TO_QUEUE;
                }
                break;
        }
    }

    return whatToDoWithThisEvent;
}

In my case, I have a wrapper around SDL that I call IHardwareLayer, and it will delegate the calls to SDL as well as do some other useful things.

The above code worked fine. Before I added this event filtering, my music-playing Android app would become unresponsive whenever the app would get suspended. With SDL2 and SDL2_mixer, the music plays on a separate thread, but most of the time you don’t need to know about it. In this case, however, you need to stop the music before your app gets suspended in order to prevent it from trying to play music in a bad state.

Ok, great! But then I updated my libraries in order to handle the ability to load SVGs, and the above code started failing. Except suspending worked just fine. It was the resume functionality that was broken now. How bizarre!

So the symptom is that when the app is suspended, everything is fine, but bringing the app back to the foreground would cause it to become unresponsive.

By adding logs and using adb logcat, I could trace the code all the way until it called Mix_ResumeMusic(), and it never returned from the call. What gives?

After trying a number of different approaches, including updating SDL2_mixer to the latest release, I finally tried to resume the music in the main event loop.
I presume the issue has to do with threading, as I learned I couldn’t call functions that would let me query the pause state of the music in the event filter without the app becoming unresponsive.

The way the event filter works, it gets called before your main event loop, giving you a chance to handle an event beforehand. You can, of course, ignore an event, and in my code above, the default return value ADD_TO_QUEUE is an int that has a value of 1, which has the effect of allowing the event to get handled later in my main event loop when I call SDL_PollEvent().

So I changed the above code so that it no longer tries to resume music and it no longer returns DO_NOT_ADD_TO_QUEUE (otherwise known as the return value of 0) when the filter receives the event SDL_APP_DIDENTERFOREGROUND. Then I added the following code to my main event loop, which is in my HardwareLayer wrapper class:

SDL_Event event;
while (1 == SDL_PollEvent(&event))
{
    switch (event.type)
    {
        case SDL_APP_DIDENTERFOREGROUND:
            {
                resumeMusic(); 
            }
            break;

...

So now I pause the music when handling the SDL_APP_WILLENTERBACKGROUND event in the event filter, and I resume music once my app is up and running the main event loop again. No more crashes or unresponsive app!

I am a bit bothered by the lack of symmetry in terms of how to handle suspending and resuming an app, but software development is often about compromise. B-)

Slides from My Presentation at #dsmAgile: “You Are Not a Code Monkey So Stop Acting Like One!”

The relationship between organizations and IT can be quite dysfunctional, and unfortunately they grew up together thinking poor results and demoralizing interactions are perfectly normal.

Developers tend to learn they have no control over their situation, which is unfortunate because they have so much more to offer an organization than merely following orders and writing code to a specification. Some internalize their status of “code monkey” and even take pride in it.

Organizations want efficiency, but then behave in ways that discourage developers from helping them actually become more efficient, and developers behave in ways that give organizations no reason to even think to ask developers for their input.

At dsmAgile 2018, my presentation “You Are Not a Code Monkey So Stop Acting Like One!” seemed well-received, and I had a number of people come up to me afterward to ask if I had been in their organization recently.

You can download the slides here:

Based on conversation I had at the conference, I think I should have focused a bit more on hope for the future and less on itemizing the symptoms and illustrating the problem. My goal was to ask developers and organizations to step up and treat each other as partners, and not to provide ammo for a gripe session. Next time…

What are your thoughts? Do you feel your organization treats you as a partner or as a code monkey?

Come See Me Speak at dsmAgile on September 28th

dsmAgile is a one day Agile conference in Des Moines, Iowa, and I’ll be presenting at it this year.

On Friday, September 28, 2018 from 8:30 AM to 4:30 PM, you can discuss, discover, and learn more about Agile software development from people who have been practicing and living it. And it only costs $100, a great deal.

My presentation is called “You’re Not a Code Monkey, So Stop Acting Like One!” You can read more about in the dsmAgile session descriptions, but the main idea is that software developers can and should do more than write code.

You are responsible for not only creating value through technology but also for maintaining that capability, and you don’t get to pretend that “they won’t let me” is a valid excuse.

Merely slinging code is not enough. You are not a code monkey following orders. You are a first-class citizen in the organization, more than capable of driving value as well as delivering it. Let’s discuss how you (and your organization) can start acting like it.

I have enjoyed attending dsmAgile in the last few years, and I look forward to being part it. Will I see you there?

A Goodbye to Diego, My Favorite Pair Partner

At 2:44am, I watched my cat Diego take his final breath. He was about 15 years old, and I knew him for 12 of those years.

Diego

12 years ago, I was living in Chicago and visiting friends in Iowa, and I learned that their neighbor’s daughter was getting married to someone who was deathly allergic to her cats. She was looking for a new home for them, and since I happened to be interested in getting a couple of cats at the time, I took in Diego and his sister Gizmo when they were three years old.

I was told that he was named Diego because he looked like Diego from the movie Ice Age.

Gizmo and Diego

I quickly learned that Diego was a greeter. While his sister hid until she was sure the new people were safe, Diego was always interested in finding out who the new guests were right away.

Greeter

I remember when I was working at a company that made slot machines, and I was in crunch. So, I would leave early, come back late, and I would feel dead inside. I would plop myself onto the couch or a chair, and soon the cats would drape themselves across me. Diego would especially love to curl up with me. Napping together was great.

Me and Diego
Diego and Me
Diego cuddle time
Diego and Me

Even when I was not involved in crunch, whenever I came home, Diego would get up from whatever he was doing, meow frantically, and come see me. I would often pick him up and carry him, and he sometimes put his front paws around me like he was a child being carried by a parent.

I would whistle a certain way, and he often meowed in response, and every so often he would come to me, which was a neat party trick, except he never seemed to want to do it at parties or when other people were present.

Diego is hamming it up

Diego and his sister have been with me through five moves, two states, multiple Ludum Dare competitions, three jobs, and a few relationships. He has been my constant companion for almost a third of my life.

I don’t remember exactly when I realized he was growing old, but it was within the last few years. I might have been tossing him one of his toys and noticing that he was less interested in chasing it. He moved a little slower. But he was still playful, and he was fairly healthy throughout his life. I had to take him to the vet once to get some of his teeth pulled because they were not healthy, but he was fine.

I felt, however, I was on notice, and I realized that one day he might not be around anymore.

In the past couple of months, Gizmo had high blood glucose levels, and so she was on insulin to see if it would help. I changed their diet from dry food to wet food, as I read it can help with reversing diabetes. Gizmo’s levels dropped to the point that she no longer needed insulin, and she eventually bounced back to her old self.

Unfortunately, since I was so focused on Gizmo’s health and her eating habits, I didn’t notice when Diego stopped eating and drinking. They both lost weight, but I chalked it up to a better diet (they were both a bit on the heavy side), but at one point I realized that Diego felt a lot bonier than I could remember. I started to find him hanging out in strange areas, such as the upstairs bathroom, which is never a good sign in cats.

Last week we took him to a vet, and we made an appointment for an ultrasound for this coming Monday, but Diego’s health rapidly declined. It was very quick how he went from seeming perfectly fine to being on his death bed. I checked up on him throughout the day yesterday, but he got so weak that he could barely hold himself up.

My wife and I took shifts to stay with him last night, and when it was my turn, I found he was breathing very shallow breaths. He yowled a bit, and I had no idea if he could see me. I sang to him, talked to him, and pet him. I noticed his paw twitching, and every so often he would take a very large breath, stop breathing for a moment, then pick back up with the shallow breaths. It was awful.

At one point, I saw him stretch his paw out in front of him, which was a lot more movement than I had seen in a long while. A few moments later, he reared his head back, let out a deep groan of a sigh, and he was gone.

I am devastated. I don’t know why his health suddenly got so bad, and I hate that I didn’t see it earlier. I wish he didn’t have to go through as much suffering in his final moments as he did.

Diego, I love you. I will miss the way you climbed onto me whenever I was sitting or lying down. I will miss scratching you under your chin and seeing you close your eyes in contentment. I will miss dancing with you. I will miss your hugs. I will miss how you and Gizmo would curl up to sleep together. I will miss how it feels to come home and have you be one of the first to greet me as I walk in the door. I will miss how you would reach up to my face and pull it towards yours, probably to smell my breath or lick my chin.

I miss you.

My Favorite Pair Partner

Don’t Pigeonhole Me: In Defense of the Jack of All Trades

Back when I was going to school at DePaul University in Chicago, the computer science school was introducing a game development minor. To kick it off, they had a panel involving a few people from local game companies such as Midway and Volition, as well as a few members of the Xbox team from Microsoft.

I remember the vice president from Midway Games answering a question from the students in the audience about how to get into the game industry. He referred to some advice that had shown up somewhere from Midway’s HR that essentially said, “Specialize, don’t generalize.”

I remember not liking that advice then, and I still don’t like it now. It sounded to me like “pigeonhole yourself and don’t you dare try to step outside of your hole”. Telling students who are interested in a future career, “You can improve your skills, but only in this one area of life” sounds overly restrictive and a path to misery. Or at least getting let go when your limited expertise is no longer needed.

Two Pigeons

Now, specializing isn’t necessarily bad advice. It’s just not the only valid option, and yet people like to talk as if it is.

I was catching up on my news feeds and saw that artist David M. Kessler wrote If You’re Talking to Everybody, You’re Talking to Nobody.

Don’t be a jack-of-all-trades. Pick what you like to do best, then get really good at it. Try to be better than anybody else. Let people see that you are an expert at the “thing” you do.

When you get known for that one “thing” you’ll see your art career soar. Now get in that pigeonhole and start working on your “thing.”

He says “Any successful marketer and business owner knows that you have to focus your efforts in order to target your market for sales. If you can’t target a market, you won’t make any sales – that’s business 101.”

He’s not wrong about needing a target market, but I don’t think “targeting your market for sales” is synonymous with pigeon-holing yourself into a single specialty.

He listed a bunch of artists as examples to further his point. The idea being that if you think of someone such as Monet or Jackson Pollock, you will inevitably call to mind some representative work of theirs.

But then, what about an artist such as Leonardo da Vinci? What was his “thing”? What about Leon Battista Alberti? Did he have just one thing?

How about someone more contemporary, such as Viggo Mortensen? I knew he was an actor from his role in Lord of the Rings, but I learned he is also an abstract painter and a poet, among other things.

There’s a lot of advice about specializing, and often it is very good advice, but just as often it is also not really supported by any sort of economic principle. Rather it’s more like “common wisdom” that “everyone” knows.

There’s no actual need to pigeonhole yourself into a specialty. Maybe it’s a tougher route to communicate your “thing”, since someone else can’t easily pigeonhole you as an abstract painter, but no one said it had to be easy.

Maybe rather than thinking about arbitrarily self-imposed limits, the more important thing is finding the thread that ties your story together as Pamela Slim argues in her book Body of Work.

Apple makes a lot of different products. Their thing isn’t merely iPhones or Macs. Their “thing” is elegantly, well-designed computing devices. Their “thing” is bigger than what a single product can encompass.

Telling executives at one of the most financially successful businesses in the world “Stop it. You need to niche down” wouldn’t make sense, would it?

The benefits to a focused approach are more than just increased sales. As you begin to focus your work, you’ll begin to get really good at it – better than you thought possible.

While I can see the logic, I also think that I could see someone get really good at their craft if they are able to work with different approaches, techniques, and mediums.

If all you know is oil painting, maybe you’ll get really good at oil painting. But if you know water color as well?

And if you think, “Huh, I wonder how it would look if part of the painting was oil but part was water color?” Would the result potentially be a more interesting work? Would the skill developed in each medium overlap, complement, or reinforce the other?

I don’t know, but I bet a conversation with someone who focused on creating the best work they could with all of their varied skills would be more fascinating and interesting than someone who is Yet Another Oil Painter.

And if their work is more fascinating and interesting, would commercial success also be possible?

According to Vigo Mortensen’s Wikipedia entry, “Mortensen experiments with his poetry and music by mixing the two art forms.”

Do you think his work in one influences the other and makes him a better artist, or does it reduce him to mediocrity because of a lack of focus? How about his music and his film efforts?

Dismissing the jack-of-all-trades as doomed to financial failure easy, but I see no supporting evidence. In fact, in software development, there’s a premium on so-called “full-stack” developers. Rather than hiring someone who only knows how to work with back-end databases or front-end forms, you get yourself a programmer who can do both as well as everything in between.

No one says, “Oh, sorry. we’re looking for a programmer who only knows one kind of programming language.” That’s like saying, “We want programmers who can’t think beyond one paradigm.”

On the other hand, a jack-of-all-trades without a larger purpose, vision, or mission? THAT I can see as being a problem, financially and otherwise.

Follow GBGames on Google Plus and Facebook!


Twitter: gbgames