0

I have a working app that receives Bluetooth-lowenergy notifications and responds by sending data back to the source in an async thread. I noticed under Android 8 the app is suspended along with the data send when pushed to the background. Can this be turned off or do I need to revamp the app as a Service and will the app continue to receive Bluetooth callbacks like Characteristic Changed notifications?

Update 1. I'm not able to get a real device running Oreo to test the background sleep so I created a virtual Pixel 2 running 8.1 and ran the following code in onCreate(). Surprisingly the background thread keept running on time even after opening the phone and browser apps.

    Thread workThread = new Thread(new Runnable()
    {
        public void run()
        {
            int i = 0;

            try
            {
                while (true)
                {
                    Log.d(LOGTAG, "Work Thread: " + i++);
                    Thread.sleep(500);
                }
            }
            catch (InterruptedException ie)
            {
                Log.d(LOGTAG, "Work Thread interrupted");
            }
            catch(Exception e)
            {
                Log.d(LOGTAG, "Work Thread error: " + e.toString());
            }

            Log.d(LOGTAG, "Work thread stopped");
        }
    });

    workThread.start();
glez
  • 1,170
  • 3
  • 16
  • 42

1 Answers1

1

As you noticed, it is a new Normal for Android Developers. Android Documentation on Background services put a note that:

If your app targets API level 26 or higher, the system imposes restrictions on running background services when the app itself isn't in the foreground. In most cases like this, your app should use a scheduled job instead.

So you will need to user some sort of scheduling your stuffs when your app goes to the background somehow. The recommended way is to use WorkManager which is part of Google's JetPack. A note on the same page makes it clear that:

WorkManager is intended for tasks that require a guarantee that the system will run them even if the app exits, like uploading app data to a server. It is not intended for in-process background work that can safely be terminated if the app process goes away; for situations like that, we recommend using ThreadPools.

There is Android Jobs too, but the author recommends that his users start switching to WorkManager, so it makes no sense to start using it at this point

Stefano Mtangoo
  • 6,017
  • 6
  • 47
  • 93
  • The background thread can be killed when the app exits. I thought creating a new Runable was using a thread pool. – glez Jul 02 '18 at 19:59
  • It is not killed if you follow the recommended way. Otherwise there are no guarantees that your thread will live... – Stefano Mtangoo Jul 03 '18 at 09:26